livekit-server-sdk 2.10.2 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,6 +35,7 @@ module.exports = __toCommonJS(AccessToken_exports);
35
35
  var jose = __toESM(require("jose"), 1);
36
36
  var import_grants = require("./grants.cjs");
37
37
  const defaultTTL = `6h`;
38
+ const defaultClockToleranceSeconds = 10;
38
39
  class AccessToken {
39
40
  /**
40
41
  * Creates a new AccessToken
@@ -152,9 +153,12 @@ class TokenVerifier {
152
153
  this.apiKey = apiKey;
153
154
  this.apiSecret = apiSecret;
154
155
  }
155
- async verify(token) {
156
+ async verify(token, clockTolerance = defaultClockToleranceSeconds) {
156
157
  const secret = new TextEncoder().encode(this.apiSecret);
157
- const { payload } = await jose.jwtVerify(token, secret, { issuer: this.apiKey });
158
+ const { payload } = await jose.jwtVerify(token, secret, {
159
+ issuer: this.apiKey,
160
+ clockTolerance
161
+ });
158
162
  if (!payload) {
159
163
  throw Error("invalid token");
160
164
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/AccessToken.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { RoomConfiguration } from '@livekit/protocol';\nimport * as jose from 'jose';\nimport type { ClaimGrants, SIPGrant, VideoGrant } from './grants.js';\nimport { claimsToJwtPayload } from './grants.js';\n\n// 6 hours\nconst defaultTTL = `6h`;\n\nexport interface AccessTokenOptions {\n /**\n * amount of time before expiration\n * expressed in seconds or a string describing a time span zeit/ms.\n * eg: '2 days', '10h', or seconds as numeric value\n */\n ttl?: number | string;\n\n /**\n * display name for the participant, available as `Participant.name`\n */\n name?: string;\n\n /**\n * identity of the user, required for room join tokens\n */\n identity?: string;\n\n /**\n * custom metadata to be passed to participants\n */\n metadata?: string;\n\n /**\n * custom attributes to be passed to participants\n */\n attributes?: Record<string, string>;\n}\n\nexport class AccessToken {\n private apiKey: string;\n\n private apiSecret: string;\n\n private grants: ClaimGrants;\n\n identity?: string;\n\n ttl: number | string;\n\n /**\n * Creates a new AccessToken\n * @param apiKey - API Key, can be set in env LIVEKIT_API_KEY\n * @param apiSecret - Secret, can be set in env LIVEKIT_API_SECRET\n */\n constructor(apiKey?: string, apiSecret?: string, options?: AccessTokenOptions) {\n if (!apiKey) {\n apiKey = process.env.LIVEKIT_API_KEY;\n }\n if (!apiSecret) {\n apiSecret = process.env.LIVEKIT_API_SECRET;\n }\n if (!apiKey || !apiSecret) {\n throw Error('api-key and api-secret must be set');\n }\n // @ts-expect-error we're not including dom lib for the server sdk so document is not defined\n else if (typeof document !== 'undefined') {\n // check against document rather than window because deno provides window\n console.error(\n 'You should not include your API secret in your web client bundle.\\n\\n' +\n 'Your web client should request a token from your backend server which should then use ' +\n 'the API secret to generate a token. See https://docs.livekit.io/client/connect/',\n );\n }\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n this.grants = {};\n this.identity = options?.identity;\n this.ttl = options?.ttl || defaultTTL;\n if (typeof this.ttl === 'number') {\n this.ttl = `${this.ttl}s`;\n }\n if (options?.metadata) {\n this.metadata = options.metadata;\n }\n if (options?.attributes) {\n this.attributes = options.attributes;\n }\n if (options?.name) {\n this.name = options.name;\n }\n }\n\n /**\n * Adds a video grant to this token.\n * @param grant -\n */\n addGrant(grant: VideoGrant) {\n this.grants.video = { ...(this.grants.video ?? {}), ...grant };\n }\n\n /**\n * Adds a SIP grant to this token.\n * @param grant -\n */\n addSIPGrant(grant: SIPGrant) {\n this.grants.sip = { ...(this.grants.sip ?? {}), ...grant };\n }\n\n get name(): string | undefined {\n return this.grants.name;\n }\n\n set name(name: string) {\n this.grants.name = name;\n }\n\n get metadata(): string | undefined {\n return this.grants.metadata;\n }\n\n /**\n * Set metadata to be passed to the Participant, used only when joining the room\n */\n set metadata(md: string) {\n this.grants.metadata = md;\n }\n\n get attributes(): Record<string, string> | undefined {\n return this.grants.attributes;\n }\n\n set attributes(attrs: Record<string, string>) {\n this.grants.attributes = attrs;\n }\n\n get kind(): string | undefined {\n return this.grants.kind;\n }\n\n set kind(kind: string) {\n this.grants.kind = kind;\n }\n\n get sha256(): string | undefined {\n return this.grants.sha256;\n }\n\n set sha256(sha: string | undefined) {\n this.grants.sha256 = sha;\n }\n\n get roomPreset(): string | undefined {\n return this.grants.roomPreset;\n }\n\n set roomPreset(preset: string | undefined) {\n this.grants.roomPreset = preset;\n }\n\n get roomConfig(): RoomConfiguration | undefined {\n return this.grants.roomConfig;\n }\n\n set roomConfig(config: RoomConfiguration | undefined) {\n this.grants.roomConfig = config;\n }\n\n /**\n * @returns JWT encoded token\n */\n async toJwt(): Promise<string> {\n // TODO: check for video grant validity\n\n const secret = new TextEncoder().encode(this.apiSecret);\n\n const jwt = new jose.SignJWT(claimsToJwtPayload(this.grants))\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuer(this.apiKey)\n .setExpirationTime(this.ttl)\n .setNotBefore(0);\n if (this.identity) {\n jwt.setSubject(this.identity);\n } else if (this.grants.video?.roomJoin) {\n throw Error('identity is required for join but not set');\n }\n return jwt.sign(secret);\n }\n}\n\nexport class TokenVerifier {\n private apiKey: string;\n\n private apiSecret: string;\n\n constructor(apiKey: string, apiSecret: string) {\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n }\n\n async verify(token: string): Promise<ClaimGrants> {\n const secret = new TextEncoder().encode(this.apiSecret);\n const { payload } = await jose.jwtVerify(token, secret, { issuer: this.apiKey });\n if (!payload) {\n throw Error('invalid token');\n }\n\n return payload as ClaimGrants;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,WAAsB;AAEtB,oBAAmC;AAGnC,MAAM,aAAa;AA+BZ,MAAM,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBvB,YAAY,QAAiB,WAAoB,SAA8B;AAC7E,QAAI,CAAC,QAAQ;AACX,eAA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AAI,YAAY,EAAE,OAAO,KAAK,SAAS;AACtD,UAAM,EAAE,QAAQ,IAAI,MAAM,KAAK,UAAU,OAAO,QAAQ,EAAE,QAAQ,KAAK,OAAO,CAAC;AAC/E,QAAI,CAAC,SAAS;AACZ,YAAM,MAAM,eAAe;AAAA,IAC7B;AAEA,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/AccessToken.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { RoomConfiguration } from '@livekit/protocol';\nimport * as jose from 'jose';\nimport type { ClaimGrants, SIPGrant, VideoGrant } from './grants.js';\nimport { claimsToJwtPayload } from './grants.js';\n\n// 6 hours\nconst defaultTTL = `6h`;\n\nconst defaultClockToleranceSeconds = 10;\n\nexport interface AccessTokenOptions {\n /**\n * amount of time before expiration\n * expressed in seconds or a string describing a time span zeit/ms.\n * eg: '2 days', '10h', or seconds as numeric value\n */\n ttl?: number | string;\n\n /**\n * display name for the participant, available as `Participant.name`\n */\n name?: string;\n\n /**\n * identity of the user, required for room join tokens\n */\n identity?: string;\n\n /**\n * custom metadata to be passed to participants\n */\n metadata?: string;\n\n /**\n * custom attributes to be passed to participants\n */\n attributes?: Record<string, string>;\n}\n\nexport class AccessToken {\n private apiKey: string;\n\n private apiSecret: string;\n\n private grants: ClaimGrants;\n\n identity?: string;\n\n ttl: number | string;\n\n /**\n * Creates a new AccessToken\n * @param apiKey - API Key, can be set in env LIVEKIT_API_KEY\n * @param apiSecret - Secret, can be set in env LIVEKIT_API_SECRET\n */\n constructor(apiKey?: string, apiSecret?: string, options?: AccessTokenOptions) {\n if (!apiKey) {\n apiKey = process.env.LIVEKIT_API_KEY;\n }\n if (!apiSecret) {\n apiSecret = process.env.LIVEKIT_API_SECRET;\n }\n if (!apiKey || !apiSecret) {\n throw Error('api-key and api-secret must be set');\n }\n // @ts-expect-error we're not including dom lib for the server sdk so document is not defined\n else if (typeof document !== 'undefined') {\n // check against document rather than window because deno provides window\n console.error(\n 'You should not include your API secret in your web client bundle.\\n\\n' +\n 'Your web client should request a token from your backend server which should then use ' +\n 'the API secret to generate a token. See https://docs.livekit.io/client/connect/',\n );\n }\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n this.grants = {};\n this.identity = options?.identity;\n this.ttl = options?.ttl || defaultTTL;\n if (typeof this.ttl === 'number') {\n this.ttl = `${this.ttl}s`;\n }\n if (options?.metadata) {\n this.metadata = options.metadata;\n }\n if (options?.attributes) {\n this.attributes = options.attributes;\n }\n if (options?.name) {\n this.name = options.name;\n }\n }\n\n /**\n * Adds a video grant to this token.\n * @param grant -\n */\n addGrant(grant: VideoGrant) {\n this.grants.video = { ...(this.grants.video ?? {}), ...grant };\n }\n\n /**\n * Adds a SIP grant to this token.\n * @param grant -\n */\n addSIPGrant(grant: SIPGrant) {\n this.grants.sip = { ...(this.grants.sip ?? {}), ...grant };\n }\n\n get name(): string | undefined {\n return this.grants.name;\n }\n\n set name(name: string) {\n this.grants.name = name;\n }\n\n get metadata(): string | undefined {\n return this.grants.metadata;\n }\n\n /**\n * Set metadata to be passed to the Participant, used only when joining the room\n */\n set metadata(md: string) {\n this.grants.metadata = md;\n }\n\n get attributes(): Record<string, string> | undefined {\n return this.grants.attributes;\n }\n\n set attributes(attrs: Record<string, string>) {\n this.grants.attributes = attrs;\n }\n\n get kind(): string | undefined {\n return this.grants.kind;\n }\n\n set kind(kind: string) {\n this.grants.kind = kind;\n }\n\n get sha256(): string | undefined {\n return this.grants.sha256;\n }\n\n set sha256(sha: string | undefined) {\n this.grants.sha256 = sha;\n }\n\n get roomPreset(): string | undefined {\n return this.grants.roomPreset;\n }\n\n set roomPreset(preset: string | undefined) {\n this.grants.roomPreset = preset;\n }\n\n get roomConfig(): RoomConfiguration | undefined {\n return this.grants.roomConfig;\n }\n\n set roomConfig(config: RoomConfiguration | undefined) {\n this.grants.roomConfig = config;\n }\n\n /**\n * @returns JWT encoded token\n */\n async toJwt(): Promise<string> {\n // TODO: check for video grant validity\n\n const secret = new TextEncoder().encode(this.apiSecret);\n\n const jwt = new jose.SignJWT(claimsToJwtPayload(this.grants))\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuer(this.apiKey)\n .setExpirationTime(this.ttl)\n .setNotBefore(0);\n if (this.identity) {\n jwt.setSubject(this.identity);\n } else if (this.grants.video?.roomJoin) {\n throw Error('identity is required for join but not set');\n }\n return jwt.sign(secret);\n }\n}\n\nexport class TokenVerifier {\n private apiKey: string;\n\n private apiSecret: string;\n\n constructor(apiKey: string, apiSecret: string) {\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n }\n\n async verify(\n token: string,\n clockTolerance: string | number = defaultClockToleranceSeconds,\n ): Promise<ClaimGrants> {\n const secret = new TextEncoder().encode(this.apiSecret);\n const { payload } = await jose.jwtVerify(token, secret, {\n issuer: this.apiKey,\n clockTolerance,\n });\n if (!payload) {\n throw Error('invalid token');\n }\n\n return payload as ClaimGrants;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,WAAsB;AAEtB,oBAAmC;AAGnC,MAAM,aAAa;AAEnB,MAAM,+BAA+B;AA+B9B,MAAM,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBvB,YAAY,QAAiB,WAAoB,SAA8B;AAC7E,QAAI,CAAC,QAAQ;AACX,eAAS,QAAQ,IAAI;AAAA,IACvB;AACA,QAAI,CAAC,WAAW;AACd,kBAAY,QAAQ,IAAI;AAAA,IAC1B;AACA,QAAI,CAAC,UAAU,CAAC,WAAW;AACzB,YAAM,MAAM,oCAAoC;AAAA,IAClD,WAES,OAAO,aAAa,aAAa;AAExC,cAAQ;AAAA,QACN;AAAA,MAGF;AAAA,IACF;AACA,SAAK,SAAS;AACd,SAAK,YAAY;AACjB,SAAK,SAAS,CAAC;AACf,SAAK,WAAW,mCAAS;AACzB,SAAK,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76
  constructor(apiKey: string, apiSecret: string);
77
- verify(token: string): Promise<ClaimGrants>;
77
+ verify(token: string, clockTolerance?: string | number): Promise<ClaimGrants>;
78
78
  }
79
79
 
80
80
  export { AccessToken, type AccessTokenOptions, TokenVerifier };
@@ -72,6 +72,6 @@ export declare class TokenVerifier {
72
72
  private apiKey;
73
73
  private apiSecret;
74
74
  constructor(apiKey: string, apiSecret: string);
75
- verify(token: string): Promise<ClaimGrants>;
75
+ verify(token: string, clockTolerance?: string | number): Promise<ClaimGrants>;
76
76
  }
77
77
  //# sourceMappingURL=AccessToken.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"AccessToken.d.ts","sourceRoot":"","sources":["../src/AccessToken.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAE3D,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAMrE,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAEtB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACrC;AAED,qBAAa,WAAW;IACtB,OAAO,CAAC,MAAM,CAAS;IAEvB,OAAO,CAAC,SAAS,CAAS;IAE1B,OAAO,CAAC,MAAM,CAAc;IAE5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;IAErB;;;;OAIG;gBACS,MAAM,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,kBAAkB;IAsC7E;;;OAG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IAAI,IAAI,MAAM,GAAG,SAAS,CAE7B;IAED,IAAI,IAAI,CAAC,IAAI,EAAE,MAAM,EAEpB;IAED,IAAI,MAAM,IAAI,MAAM,GAAG,SAAS,CAE/B;IAED,IAAI,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,EAEjC;IAED,IAAI,UAAU,IAAI,MAAM,GAAG,SAAS,CAEnC;IAED,IAAI,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,EAExC;IAED,IAAI,UAAU,IAAI,iBAAiB,GAAG,SAAS,CAE9C;IAED,IAAI,UAAU,CAAC,MAAM,EAAE,iBAAiB,GAAG,SAAS,EAEnD;IAED;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;CAiB/B;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAS;IAEvB,OAAO,CAAC,SAAS,CAAS;gBAEd,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;IAKvC,MAAM,CACV,KAAK,EAAE,MAAM,EACb,cAAc,GAAE,MAAM,GAAG,MAAqC,GAC7D,OAAO,CAAC,WAAW,CAAC;CAYxB"}
@@ -1,6 +1,7 @@
1
1
  import * as jose from "jose";
2
2
  import { claimsToJwtPayload } from "./grants.js";
3
3
  const defaultTTL = `6h`;
4
+ const defaultClockToleranceSeconds = 10;
4
5
  class AccessToken {
5
6
  /**
6
7
  * Creates a new AccessToken
@@ -118,9 +119,12 @@ class TokenVerifier {
118
119
  this.apiKey = apiKey;
119
120
  this.apiSecret = apiSecret;
120
121
  }
121
- async verify(token) {
122
+ async verify(token, clockTolerance = defaultClockToleranceSeconds) {
122
123
  const secret = new TextEncoder().encode(this.apiSecret);
123
- const { payload } = await jose.jwtVerify(token, secret, { issuer: this.apiKey });
124
+ const { payload } = await jose.jwtVerify(token, secret, {
125
+ issuer: this.apiKey,
126
+ clockTolerance
127
+ });
124
128
  if (!payload) {
125
129
  throw Error("invalid token");
126
130
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/AccessToken.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { RoomConfiguration } from '@livekit/protocol';\nimport * as jose from 'jose';\nimport type { ClaimGrants, SIPGrant, VideoGrant } from './grants.js';\nimport { claimsToJwtPayload } from './grants.js';\n\n// 6 hours\nconst defaultTTL = `6h`;\n\nexport interface AccessTokenOptions {\n /**\n * amount of time before expiration\n * expressed in seconds or a string describing a time span zeit/ms.\n * eg: '2 days', '10h', or seconds as numeric value\n */\n ttl?: number | string;\n\n /**\n * display name for the participant, available as `Participant.name`\n */\n name?: string;\n\n /**\n * identity of the user, required for room join tokens\n */\n identity?: string;\n\n /**\n * custom metadata to be passed to participants\n */\n metadata?: string;\n\n /**\n * custom attributes to be passed to participants\n */\n attributes?: Record<string, string>;\n}\n\nexport class AccessToken {\n private apiKey: string;\n\n private apiSecret: string;\n\n private grants: ClaimGrants;\n\n identity?: string;\n\n ttl: number | string;\n\n /**\n * Creates a new AccessToken\n * @param apiKey - API Key, can be set in env LIVEKIT_API_KEY\n * @param apiSecret - Secret, can be set in env LIVEKIT_API_SECRET\n */\n constructor(apiKey?: string, apiSecret?: string, options?: AccessTokenOptions) {\n if (!apiKey) {\n apiKey = process.env.LIVEKIT_API_KEY;\n }\n if (!apiSecret) {\n apiSecret = process.env.LIVEKIT_API_SECRET;\n }\n if (!apiKey || !apiSecret) {\n throw Error('api-key and api-secret must be set');\n }\n // @ts-expect-error we're not including dom lib for the server sdk so document is not defined\n else if (typeof document !== 'undefined') {\n // check against document rather than window because deno provides window\n console.error(\n 'You should not include your API secret in your web client bundle.\\n\\n' +\n 'Your web client should request a token from your backend server which should then use ' +\n 'the API secret to generate a token. See https://docs.livekit.io/client/connect/',\n );\n }\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n this.grants = {};\n this.identity = options?.identity;\n this.ttl = options?.ttl || defaultTTL;\n if (typeof this.ttl === 'number') {\n this.ttl = `${this.ttl}s`;\n }\n if (options?.metadata) {\n this.metadata = options.metadata;\n }\n if (options?.attributes) {\n this.attributes = options.attributes;\n }\n if (options?.name) {\n this.name = options.name;\n }\n }\n\n /**\n * Adds a video grant to this token.\n * @param grant -\n */\n addGrant(grant: VideoGrant) {\n this.grants.video = { ...(this.grants.video ?? {}), ...grant };\n }\n\n /**\n * Adds a SIP grant to this token.\n * @param grant -\n */\n addSIPGrant(grant: SIPGrant) {\n this.grants.sip = { ...(this.grants.sip ?? {}), ...grant };\n }\n\n get name(): string | undefined {\n return this.grants.name;\n }\n\n set name(name: string) {\n this.grants.name = name;\n }\n\n get metadata(): string | undefined {\n return this.grants.metadata;\n }\n\n /**\n * Set metadata to be passed to the Participant, used only when joining the room\n */\n set metadata(md: string) {\n this.grants.metadata = md;\n }\n\n get attributes(): Record<string, string> | undefined {\n return this.grants.attributes;\n }\n\n set attributes(attrs: Record<string, string>) {\n this.grants.attributes = attrs;\n }\n\n get kind(): string | undefined {\n return this.grants.kind;\n }\n\n set kind(kind: string) {\n this.grants.kind = kind;\n }\n\n get sha256(): string | undefined {\n return this.grants.sha256;\n }\n\n set sha256(sha: string | undefined) {\n this.grants.sha256 = sha;\n }\n\n get roomPreset(): string | undefined {\n return this.grants.roomPreset;\n }\n\n set roomPreset(preset: string | undefined) {\n this.grants.roomPreset = preset;\n }\n\n get roomConfig(): RoomConfiguration | undefined {\n return this.grants.roomConfig;\n }\n\n set roomConfig(config: RoomConfiguration | undefined) {\n this.grants.roomConfig = config;\n }\n\n /**\n * @returns JWT encoded token\n */\n async toJwt(): Promise<string> {\n // TODO: check for video grant validity\n\n const secret = new TextEncoder().encode(this.apiSecret);\n\n const jwt = new jose.SignJWT(claimsToJwtPayload(this.grants))\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuer(this.apiKey)\n .setExpirationTime(this.ttl)\n .setNotBefore(0);\n if (this.identity) {\n jwt.setSubject(this.identity);\n } else if (this.grants.video?.roomJoin) {\n throw Error('identity is required for join but not set');\n }\n return jwt.sign(secret);\n }\n}\n\nexport class TokenVerifier {\n private apiKey: string;\n\n private apiSecret: string;\n\n constructor(apiKey: string, apiSecret: string) {\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n }\n\n async verify(token: string): Promise<ClaimGrants> {\n const secret = new TextEncoder().encode(this.apiSecret);\n const { payload } = await jose.jwtVerify(token, secret, { issuer: this.apiKey });\n if (!payload) {\n throw Error('invalid token');\n }\n\n return payload as ClaimGrants;\n }\n}\n"],"mappings":"AAIA,YAAY,UAAU;AAEtB,SAAS,0BAA0B;AAGnC,MAAM,aAAa;AA+BZ,MAAM,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBvB,YAAY,QAAiB,WAAoB,SAA8B;AAC7E,QAAI,CAAC,QAAQ;AACX,eAAS,QAAQ,IAAI;AAAA,IACvB;AACA,QAAI,CAAC,WAAW;AACd,kBAAY,QAAQ,IAAI;AAAA,IAC1B;AACA,QAAI,CAAC,UAAU,CAAC,WAAW;AACzB,YAAM,MAAM,oCAAoC;AAAA,IAClD,WAES,OAAO,aAAa,aAAa;AAExC,cAAQ;AAAA,QACN;AAAA,MAGF;AAAA,IACF;AACA,SAAK,SAAS;AACd,SAAK,YAAY;AACjB,SAAK,SAAS,CAAC;AACf,SAAK,WAAW,mCAAS;AACzB,SAAK,OAAM,mCAAS,QAAO;AAC3B,QAAI,OAAO,KAAK,QAAQ,UAAU;AAChC,WAAK,MAAM,GAAG,KAAK,GAAG;AAAA,IACxB;AACA,QAAI,mCAAS,UAAU;AACrB,WAAK,WAAW,QAAQ;AAAA,IAC1B;AACA,QAAI,mCAAS,YAAY;AACvB,WAAK,aAAa,QAAQ;AAAA,IAC5B;AACA,QAAI,mCAAS,MAAM;AACjB,WAAK,OAAO,QAAQ;AAAA,IACtB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,OAAmB;AAC1B,SAAK,OAAO,QAAQ,EAAE,GAAI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AEtD,UAAM,MAAM,IAAI,KAAK,QAAQ,mBAAmB,KAAK,MAAM,CAAC,EACzD,mBAAmB,EAAE,KAAK,QAAQ,CAAC,EACnC,UAAU,KAAK,MAAM,EACrB,kBAAkB,KAAK,GAAG,EAC1B,aAAa,CAAC;AACjB,QAAI,KAAK,UAAU;AACjB,UAAI,WAAW,KAAK,QAAQ;AAAA,IAC9B,YAAW,UAAK,OAAO,UAAZ,mBAAmB,UAAU;AACtC,YAAM,MAAM,2CAA2C;AAAA,IACzD;AACA,WAAO,IAAI,KAAK,MAAM;AAAA,EACxB;AACF;AAEO,MAAM,cAAc;AAAA,EAKzB,YAAY,QAAgB,WAAmB;AAC7C,SAAK,SAAS;AACd,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,MAAM,OAAO,OAAqC;AAChD,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,KAAK,SAAS;AACtD,UAAM,EAAE,QAAQ,IAAI,MAAM,KAAK,UAAU,OAAO,QAAQ,EAAE,QAAQ,KAAK,OAAO,CAAC;AAC/E,QAAI,CAAC,SAAS;AACZ,YAAM,MAAM,eAAe;AAAA,IAC7B;AAEA,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/AccessToken.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { RoomConfiguration } from '@livekit/protocol';\nimport * as jose from 'jose';\nimport type { ClaimGrants, SIPGrant, VideoGrant } from './grants.js';\nimport { claimsToJwtPayload } from './grants.js';\n\n// 6 hours\nconst defaultTTL = `6h`;\n\nconst defaultClockToleranceSeconds = 10;\n\nexport interface AccessTokenOptions {\n /**\n * amount of time before expiration\n * expressed in seconds or a string describing a time span zeit/ms.\n * eg: '2 days', '10h', or seconds as numeric value\n */\n ttl?: number | string;\n\n /**\n * display name for the participant, available as `Participant.name`\n */\n name?: string;\n\n /**\n * identity of the user, required for room join tokens\n */\n identity?: string;\n\n /**\n * custom metadata to be passed to participants\n */\n metadata?: string;\n\n /**\n * custom attributes to be passed to participants\n */\n attributes?: Record<string, string>;\n}\n\nexport class AccessToken {\n private apiKey: string;\n\n private apiSecret: string;\n\n private grants: ClaimGrants;\n\n identity?: string;\n\n ttl: number | string;\n\n /**\n * Creates a new AccessToken\n * @param apiKey - API Key, can be set in env LIVEKIT_API_KEY\n * @param apiSecret - Secret, can be set in env LIVEKIT_API_SECRET\n */\n constructor(apiKey?: string, apiSecret?: string, options?: AccessTokenOptions) {\n if (!apiKey) {\n apiKey = process.env.LIVEKIT_API_KEY;\n }\n if (!apiSecret) {\n apiSecret = process.env.LIVEKIT_API_SECRET;\n }\n if (!apiKey || !apiSecret) {\n throw Error('api-key and api-secret must be set');\n }\n // @ts-expect-error we're not including dom lib for the server sdk so document is not defined\n else if (typeof document !== 'undefined') {\n // check against document rather than window because deno provides window\n console.error(\n 'You should not include your API secret in your web client bundle.\\n\\n' +\n 'Your web client should request a token from your backend server which should then use ' +\n 'the API secret to generate a token. See https://docs.livekit.io/client/connect/',\n );\n }\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n this.grants = {};\n this.identity = options?.identity;\n this.ttl = options?.ttl || defaultTTL;\n if (typeof this.ttl === 'number') {\n this.ttl = `${this.ttl}s`;\n }\n if (options?.metadata) {\n this.metadata = options.metadata;\n }\n if (options?.attributes) {\n this.attributes = options.attributes;\n }\n if (options?.name) {\n this.name = options.name;\n }\n }\n\n /**\n * Adds a video grant to this token.\n * @param grant -\n */\n addGrant(grant: VideoGrant) {\n this.grants.video = { ...(this.grants.video ?? {}), ...grant };\n }\n\n /**\n * Adds a SIP grant to this token.\n * @param grant -\n */\n addSIPGrant(grant: SIPGrant) {\n this.grants.sip = { ...(this.grants.sip ?? {}), ...grant };\n }\n\n get name(): string | undefined {\n return this.grants.name;\n }\n\n set name(name: string) {\n this.grants.name = name;\n }\n\n get metadata(): string | undefined {\n return this.grants.metadata;\n }\n\n /**\n * Set metadata to be passed to the Participant, used only when joining the room\n */\n set metadata(md: string) {\n this.grants.metadata = md;\n }\n\n get attributes(): Record<string, string> | undefined {\n return this.grants.attributes;\n }\n\n set attributes(attrs: Record<string, string>) {\n this.grants.attributes = attrs;\n }\n\n get kind(): string | undefined {\n return this.grants.kind;\n }\n\n set kind(kind: string) {\n this.grants.kind = kind;\n }\n\n get sha256(): string | undefined {\n return this.grants.sha256;\n }\n\n set sha256(sha: string | undefined) {\n this.grants.sha256 = sha;\n }\n\n get roomPreset(): string | undefined {\n return this.grants.roomPreset;\n }\n\n set roomPreset(preset: string | undefined) {\n this.grants.roomPreset = preset;\n }\n\n get roomConfig(): RoomConfiguration | undefined {\n return this.grants.roomConfig;\n }\n\n set roomConfig(config: RoomConfiguration | undefined) {\n this.grants.roomConfig = config;\n }\n\n /**\n * @returns JWT encoded token\n */\n async toJwt(): Promise<string> {\n // TODO: check for video grant validity\n\n const secret = new TextEncoder().encode(this.apiSecret);\n\n const jwt = new jose.SignJWT(claimsToJwtPayload(this.grants))\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuer(this.apiKey)\n .setExpirationTime(this.ttl)\n .setNotBefore(0);\n if (this.identity) {\n jwt.setSubject(this.identity);\n } else if (this.grants.video?.roomJoin) {\n throw Error('identity is required for join but not set');\n }\n return jwt.sign(secret);\n }\n}\n\nexport class TokenVerifier {\n private apiKey: string;\n\n private apiSecret: string;\n\n constructor(apiKey: string, apiSecret: string) {\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n }\n\n async verify(\n token: string,\n clockTolerance: string | number = defaultClockToleranceSeconds,\n ): Promise<ClaimGrants> {\n const secret = new TextEncoder().encode(this.apiSecret);\n const { payload } = await jose.jwtVerify(token, secret, {\n issuer: this.apiKey,\n clockTolerance,\n });\n if (!payload) {\n throw Error('invalid token');\n }\n\n return payload as ClaimGrants;\n }\n}\n"],"mappings":"AAIA,YAAY,UAAU;AAEtB,SAAS,0BAA0B;AAGnC,MAAM,aAAa;AAEnB,MAAM,+BA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AAAA,EAKzB,YAAY,QAAgB,WAAmB;AAC7C,SAAK,SAAS;AACd,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,MAAM,OACJ,OACA,iBAAkC,8BACZ;AACtB,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,KAAK,SAAS;AACtD,UAAM,EAAE,QAAQ,IAAI,MAAM,KAAK,UAAU,OAAO,QAAQ;AAAA,MACtD,QAAQ,KAAK;AAAA,MACb;AAAA,IACF,CAAC;AACD,QAAI,CAAC,SAAS;AACZ,YAAM,MAAM,eAAe;AAAA,IAC7B;AAEA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -134,6 +134,23 @@ class RoomServiceClient extends import_ServiceBase.ServiceBase {
134
134
  await this.authHeader({ roomAdmin: true, room })
135
135
  );
136
136
  }
137
+ /**
138
+ * Forwards a participant's track to another room. This will create a
139
+ * participant to join the destination room that has same information
140
+ * with the source participant except the kind to be `Forwarded`. All
141
+ * changes to the source participant will be reflected to the forwarded
142
+ * participant. When the source participant disconnects or the
143
+ * `RemoveParticipant` method is called in the destination room, the
144
+ * forwarding will be stopped.
145
+ */
146
+ async forwardParticipant(room, identity, destinationRoom) {
147
+ await this.rpc.request(
148
+ svc,
149
+ "ForwardParticipant",
150
+ new import_protocol.ForwardParticipantRequest({ room, identity, destinationRoom }).toJson(),
151
+ await this.authHeader({ roomAdmin: true, room })
152
+ );
153
+ }
137
154
  /**
138
155
  * Mutes a track that the participant has published.
139
156
  * @param room -
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/RoomServiceClient.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { DataPacket_Kind, RoomEgress, TrackInfo } from '@livekit/protocol';\nimport {\n CreateRoomRequest,\n DeleteRoomRequest,\n ListParticipantsRequest,\n ListParticipantsResponse,\n ListRoomsRequest,\n ListRoomsResponse,\n MuteRoomTrackRequest,\n MuteRoomTrackResponse,\n ParticipantInfo,\n ParticipantPermission,\n Room,\n RoomParticipantIdentity,\n SendDataRequest,\n UpdateParticipantRequest,\n UpdateRoomMetadataRequest,\n UpdateSubscriptionsRequest,\n} from '@livekit/protocol';\nimport { ServiceBase } from './ServiceBase.js';\nimport type { Rpc } from './TwirpRPC.js';\nimport { TwirpRpc, livekitPackage } from './TwirpRPC.js';\nimport { getRandomBytes } from './crypto/uuid.js';\n\n/**\n * Options for when creating a room\n */\nexport interface CreateOptions {\n /**\n * name of the room. required\n */\n name: string;\n\n /**\n * number of seconds to keep the room open before any participant joins\n */\n emptyTimeout?: number;\n\n /**\n * number of seconds to keep the room open after the last participant leaves\n * this option is helpful to give a grace period for participants to re-join\n */\n departureTimeout?: number;\n\n /**\n * limit to the number of participants in a room at a time\n */\n maxParticipants?: number;\n\n /**\n * initial room metadata\n */\n metadata?: string;\n\n /**\n * add egress options\n */\n egress?: RoomEgress;\n\n /**\n * minimum playout delay in milliseconds\n */\n minPlayoutDelay?: number;\n\n /**\n * maximum playout delay in milliseconds\n */\n maxPlayoutDelay?: number;\n\n /**\n * improves A/V sync when min_playout_delay set to a value larger than 200ms.\n * It will disables transceiver re-use -- this option is not recommended\n * for rooms with frequent subscription changes\n */\n syncStreams?: boolean;\n\n /**\n * override the node room is allocated to, for debugging\n * does not work with Cloud\n */\n nodeId?: string;\n}\n\nexport type SendDataOptions = {\n /** If set, only deliver to listed participant identities */\n destinationIdentities?: string[];\n destinationSids?: string[];\n topic?: string;\n};\n\nexport type UpdateParticipantOptions = {\n /** only attributes you'd want to update should be set, set value to empty string to remove it */\n attributes?: { [key: string]: string };\n metadata?: string;\n /** permissions are updated atomically - all desired permissions would need to be set */\n permission?: Partial<ParticipantPermission>;\n name?: string;\n};\n\nconst svc = 'RoomService';\n\n/**\n * Client to access Room APIs\n */\nexport class RoomServiceClient extends ServiceBase {\n private readonly rpc: Rpc;\n\n /**\n *\n * @param host - hostname including protocol. i.e. 'https://<project>.livekit.cloud'\n * @param apiKey - API Key, can be set in env var LIVEKIT_API_KEY\n * @param secret - API Secret, can be set in env var LIVEKIT_API_SECRET\n */\n constructor(host: string, apiKey?: string, secret?: string) {\n super(apiKey, secret);\n this.rpc = new TwirpRpc(host, livekitPackage);\n }\n\n /**\n * Creates a new room. Explicit room creation is not required, since rooms will\n * be automatically created when the first participant joins. This method can be\n * used to customize room settings.\n * @param options -\n */\n async createRoom(options: CreateOptions): Promise<Room> {\n const data = await this.rpc.request(\n svc,\n 'CreateRoom',\n new CreateRoomRequest(options).toJson(),\n await this.authHeader({ roomCreate: true }),\n );\n return Room.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * List active rooms\n * @param names - when undefined or empty, list all rooms.\n * otherwise returns rooms with matching names\n * @returns\n */\n async listRooms(names?: string[]): Promise<Room[]> {\n const data = await this.rpc.request(\n svc,\n 'ListRooms',\n new ListRoomsRequest({ names: names ?? [] }).toJson(),\n await this.authHeader({ roomList: true }),\n );\n const res = ListRoomsResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.rooms ?? [];\n }\n\n async deleteRoom(room: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'DeleteRoom',\n new DeleteRoomRequest({ room }).toJson(),\n await this.authHeader({ roomCreate: true }),\n );\n }\n\n /**\n * Update metadata of a room\n * @param room - name of the room\n * @param metadata - the new metadata for the room\n */\n async updateRoomMetadata(room: string, metadata: string) {\n const data = await this.rpc.request(\n svc,\n 'UpdateRoomMetadata',\n new UpdateRoomMetadataRequest({ room, metadata }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n return Room.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * List participants in a room\n * @param room - name of the room\n */\n async listParticipants(room: string): Promise<ParticipantInfo[]> {\n const data = await this.rpc.request(\n svc,\n 'ListParticipants',\n new ListParticipantsRequest({ room }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n const res = ListParticipantsResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.participants ?? [];\n }\n\n /**\n * Get information on a specific participant, including the tracks that participant\n * has published\n * @param room - name of the room\n * @param identity - identity of the participant to return\n */\n async getParticipant(room: string, identity: string): Promise<ParticipantInfo> {\n const data = await this.rpc.request(\n svc,\n 'GetParticipant',\n new RoomParticipantIdentity({ room, identity }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n\n return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * Removes a participant in the room. This will disconnect the participant\n * and will emit a Disconnected event for that participant.\n * Even after being removed, the participant can still re-join the room.\n * @param room -\n * @param identity -\n */\n async removeParticipant(room: string, identity: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'RemoveParticipant',\n new RoomParticipantIdentity({ room, identity }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Mutes a track that the participant has published.\n * @param room -\n * @param identity -\n * @param trackSid - sid of the track to be muted\n * @param muted - true to mute, false to unmute\n */\n async mutePublishedTrack(\n room: string,\n identity: string,\n trackSid: string,\n muted: boolean,\n ): Promise<TrackInfo> {\n const req = new MuteRoomTrackRequest({\n room,\n identity,\n trackSid,\n muted,\n }).toJson();\n const data = await this.rpc.request(\n svc,\n 'MutePublishedTrack',\n req,\n await this.authHeader({ roomAdmin: true, room }),\n );\n const res = MuteRoomTrackResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.track!;\n }\n\n /**\n * Updates a participant's state or permissions\n * @param room - target room\n * @param identity - participant identity\n * @param options - participant fields to update\n */\n async updateParticipant(\n room: string,\n identity: string,\n options: UpdateParticipantOptions,\n ): Promise<ParticipantInfo>;\n /**\n * Updates a participant's state or permissions\n * @param room - target room\n * @param identity - participant identity\n * @param options - participant fields to update\n */\n async updateParticipant(\n room: string,\n identity: string,\n metadata?: string,\n permission?: Partial<ParticipantPermission>,\n name?: string,\n ): Promise<ParticipantInfo>;\n async updateParticipant(\n room: string,\n identity: string,\n metadataOrOptions?: string | UpdateParticipantOptions,\n maybePermission?: Partial<ParticipantPermission>,\n maybeName?: string,\n ): Promise<ParticipantInfo> {\n const hasOptions = typeof metadataOrOptions === 'object';\n const metadata = hasOptions ? metadataOrOptions?.metadata : metadataOrOptions;\n const permission = hasOptions ? metadataOrOptions.permission : maybePermission;\n const name = hasOptions ? metadataOrOptions.name : maybeName;\n const attributes: Record<string, string> | undefined = hasOptions\n ? metadataOrOptions.attributes\n : {};\n\n const req = new UpdateParticipantRequest({\n room,\n identity,\n attributes,\n metadata,\n name,\n });\n if (permission) {\n req.permission = new ParticipantPermission(permission);\n }\n const data = await this.rpc.request(\n svc,\n 'UpdateParticipant',\n req.toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * Updates a participant's subscription to tracks\n * @param room -\n * @param identity -\n * @param trackSids -\n * @param subscribe - true to subscribe, false to unsubscribe\n */\n async updateSubscriptions(\n room: string,\n identity: string,\n trackSids: string[],\n subscribe: boolean,\n ): Promise<void> {\n const req = new UpdateSubscriptionsRequest({\n room,\n identity,\n trackSids,\n subscribe,\n participantTracks: [],\n }).toJson();\n await this.rpc.request(\n svc,\n 'UpdateSubscriptions',\n req,\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Sends data message to participants in the room\n * @param room -\n * @param data - opaque payload to send\n * @param kind - delivery reliability\n * @param options - optionally specify a topic and destinationSids (when destinationSids is empty, message is sent to everyone)\n */\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n options: SendDataOptions,\n ): Promise<void>;\n /**\n * Sends data message to participants in the room\n * @deprecated use sendData(room, data, kind, options) instead\n * @param room -\n * @param data - opaque payload to send\n * @param kind - delivery reliability\n * @param destinationSids - optional. when empty, message is sent to everyone\n */\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n destinationSids?: string[],\n ): Promise<void>;\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n options: SendDataOptions | string[] = {},\n ): Promise<void> {\n const destinationSids = Array.isArray(options) ? options : options.destinationSids;\n const topic = Array.isArray(options) ? undefined : options.topic;\n const req = new SendDataRequest({\n room,\n data,\n kind,\n destinationSids: destinationSids ?? [],\n topic,\n });\n if (!Array.isArray(options) && options.destinationIdentities) {\n req.destinationIdentities = options.destinationIdentities;\n }\n req.nonce = await getRandomBytes(16);\n await this.rpc.request(\n svc,\n 'SendData',\n req.toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,sBAiBO;AACP,yBAA4B;AAE5B,sBAAyC;AACzC,kBAA+B;AA6E/B,MAAM,MAAM;AAKL,MAAM,0BAA0B,+BAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASjD,YAAY,MAAc,QAAiB,QAAiB;AAC1D,UAAM,QAAQ,MAAM;AACpB,SAAK,MAAM,IAAI,yBAAS,MAAM,8BAAc;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,WAAW,SAAuC;AACtD,UAAM,OAAO,MAAM,KAAK,IAAI;AAAA,MAC1B;AAAA,MACA;AAAA,MACA,IAAI,kCAAkB,OAAO,EAAE,OAAO;AAAA,MACtC,MAAM,KAAK,WAAW,EAAE,YAAY,KAAK,CAAC;AAAA,IAC5C;AACA,WAAO,qBAAK,SAAS,MAAM,EAAE,qBAAqB,KAAK,CAAC;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,UAAU,OAAmC;AACjD,UAAM,OAAO,MAAM,KAAK,IAAI;AAAA,MAC1B;AAAA,MACA;AAAA,MACA,IAAI,iCAAiB,EAAE,OAAO,SAAS,CAAC,EAAE,CAAC,EAAE,OAAO;AAAA,MACpD,MAAM,KAAK,WAAW,EAAE,UAAU,KAAK,CAAC;AAAA,IAC1C;AACA,UAAM,MAAM,kCAAkB,SA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iveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { DataPacket_Kind, RoomEgress, TrackInfo } from '@livekit/protocol';\nimport {\n CreateRoomRequest,\n DeleteRoomRequest,\n ForwardParticipantRequest,\n ListParticipantsRequest,\n ListParticipantsResponse,\n ListRoomsRequest,\n ListRoomsResponse,\n MuteRoomTrackRequest,\n MuteRoomTrackResponse,\n ParticipantInfo,\n ParticipantPermission,\n Room,\n RoomParticipantIdentity,\n SendDataRequest,\n UpdateParticipantRequest,\n UpdateRoomMetadataRequest,\n UpdateSubscriptionsRequest,\n} from '@livekit/protocol';\nimport { ServiceBase } from './ServiceBase.js';\nimport type { Rpc } from './TwirpRPC.js';\nimport { TwirpRpc, livekitPackage } from './TwirpRPC.js';\nimport { getRandomBytes } from './crypto/uuid.js';\n\n/**\n * Options for when creating a room\n */\nexport interface CreateOptions {\n /**\n * name of the room. required\n */\n name: string;\n\n /**\n * number of seconds to keep the room open before any participant joins\n */\n emptyTimeout?: number;\n\n /**\n * number of seconds to keep the room open after the last participant leaves\n * this option is helpful to give a grace period for participants to re-join\n */\n departureTimeout?: number;\n\n /**\n * limit to the number of participants in a room at a time\n */\n maxParticipants?: number;\n\n /**\n * initial room metadata\n */\n metadata?: string;\n\n /**\n * add egress options\n */\n egress?: RoomEgress;\n\n /**\n * minimum playout delay in milliseconds\n */\n minPlayoutDelay?: number;\n\n /**\n * maximum playout delay in milliseconds\n */\n maxPlayoutDelay?: number;\n\n /**\n * improves A/V sync when min_playout_delay set to a value larger than 200ms.\n * It will disables transceiver re-use -- this option is not recommended\n * for rooms with frequent subscription changes\n */\n syncStreams?: boolean;\n\n /**\n * override the node room is allocated to, for debugging\n * does not work with Cloud\n */\n nodeId?: string;\n}\n\nexport type SendDataOptions = {\n /** If set, only deliver to listed participant identities */\n destinationIdentities?: string[];\n destinationSids?: string[];\n topic?: string;\n};\n\nexport type UpdateParticipantOptions = {\n /** only attributes you'd want to update should be set, set value to empty string to remove it */\n attributes?: { [key: string]: string };\n metadata?: string;\n /** permissions are updated atomically - all desired permissions would need to be set */\n permission?: Partial<ParticipantPermission>;\n name?: string;\n};\n\nconst svc = 'RoomService';\n\n/**\n * Client to access Room APIs\n */\nexport class RoomServiceClient extends ServiceBase {\n private readonly rpc: Rpc;\n\n /**\n *\n * @param host - hostname including protocol. i.e. 'https://<project>.livekit.cloud'\n * @param apiKey - API Key, can be set in env var LIVEKIT_API_KEY\n * @param secret - API Secret, can be set in env var LIVEKIT_API_SECRET\n */\n constructor(host: string, apiKey?: string, secret?: string) {\n super(apiKey, secret);\n this.rpc = new TwirpRpc(host, livekitPackage);\n }\n\n /**\n * Creates a new room. Explicit room creation is not required, since rooms will\n * be automatically created when the first participant joins. This method can be\n * used to customize room settings.\n * @param options -\n */\n async createRoom(options: CreateOptions): Promise<Room> {\n const data = await this.rpc.request(\n svc,\n 'CreateRoom',\n new CreateRoomRequest(options).toJson(),\n await this.authHeader({ roomCreate: true }),\n );\n return Room.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * List active rooms\n * @param names - when undefined or empty, list all rooms.\n * otherwise returns rooms with matching names\n * @returns\n */\n async listRooms(names?: string[]): Promise<Room[]> {\n const data = await this.rpc.request(\n svc,\n 'ListRooms',\n new ListRoomsRequest({ names: names ?? [] }).toJson(),\n await this.authHeader({ roomList: true }),\n );\n const res = ListRoomsResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.rooms ?? [];\n }\n\n async deleteRoom(room: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'DeleteRoom',\n new DeleteRoomRequest({ room }).toJson(),\n await this.authHeader({ roomCreate: true }),\n );\n }\n\n /**\n * Update metadata of a room\n * @param room - name of the room\n * @param metadata - the new metadata for the room\n */\n async updateRoomMetadata(room: string, metadata: string) {\n const data = await this.rpc.request(\n svc,\n 'UpdateRoomMetadata',\n new UpdateRoomMetadataRequest({ room, metadata }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n return Room.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * List participants in a room\n * @param room - name of the room\n */\n async listParticipants(room: string): Promise<ParticipantInfo[]> {\n const data = await this.rpc.request(\n svc,\n 'ListParticipants',\n new ListParticipantsRequest({ room }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n const res = ListParticipantsResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.participants ?? [];\n }\n\n /**\n * Get information on a specific participant, including the tracks that participant\n * has published\n * @param room - name of the room\n * @param identity - identity of the participant to return\n */\n async getParticipant(room: string, identity: string): Promise<ParticipantInfo> {\n const data = await this.rpc.request(\n svc,\n 'GetParticipant',\n new RoomParticipantIdentity({ room, identity }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n\n return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * Removes a participant in the room. This will disconnect the participant\n * and will emit a Disconnected event for that participant.\n * Even after being removed, the participant can still re-join the room.\n * @param room -\n * @param identity -\n */\n async removeParticipant(room: string, identity: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'RemoveParticipant',\n new RoomParticipantIdentity({ room, identity }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Forwards a participant's track to another room. This will create a\n * participant to join the destination room that has same information\n * with the source participant except the kind to be `Forwarded`. All\n * changes to the source participant will be reflected to the forwarded\n * participant. When the source participant disconnects or the\n * `RemoveParticipant` method is called in the destination room, the\n * forwarding will be stopped.\n */\n async forwardParticipant(room: string, identity: string, destinationRoom: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'ForwardParticipant',\n new ForwardParticipantRequest({ room, identity, destinationRoom }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Mutes a track that the participant has published.\n * @param room -\n * @param identity -\n * @param trackSid - sid of the track to be muted\n * @param muted - true to mute, false to unmute\n */\n async mutePublishedTrack(\n room: string,\n identity: string,\n trackSid: string,\n muted: boolean,\n ): Promise<TrackInfo> {\n const req = new MuteRoomTrackRequest({\n room,\n identity,\n trackSid,\n muted,\n }).toJson();\n const data = await this.rpc.request(\n svc,\n 'MutePublishedTrack',\n req,\n await this.authHeader({ roomAdmin: true, room }),\n );\n const res = MuteRoomTrackResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.track!;\n }\n\n /**\n * Updates a participant's state or permissions\n * @param room - target room\n * @param identity - participant identity\n * @param options - participant fields to update\n */\n async updateParticipant(\n room: string,\n identity: string,\n options: UpdateParticipantOptions,\n ): Promise<ParticipantInfo>;\n /**\n * Updates a participant's state or permissions\n * @param room - target room\n * @param identity - participant identity\n * @param options - participant fields to update\n */\n async updateParticipant(\n room: string,\n identity: string,\n metadata?: string,\n permission?: Partial<ParticipantPermission>,\n name?: string,\n ): Promise<ParticipantInfo>;\n async updateParticipant(\n room: string,\n identity: string,\n metadataOrOptions?: string | UpdateParticipantOptions,\n maybePermission?: Partial<ParticipantPermission>,\n maybeName?: string,\n ): Promise<ParticipantInfo> {\n const hasOptions = typeof metadataOrOptions === 'object';\n const metadata = hasOptions ? metadataOrOptions?.metadata : metadataOrOptions;\n const permission = hasOptions ? metadataOrOptions.permission : maybePermission;\n const name = hasOptions ? metadataOrOptions.name : maybeName;\n const attributes: Record<string, string> | undefined = hasOptions\n ? metadataOrOptions.attributes\n : {};\n\n const req = new UpdateParticipantRequest({\n room,\n identity,\n attributes,\n metadata,\n name,\n });\n if (permission) {\n req.permission = new ParticipantPermission(permission);\n }\n const data = await this.rpc.request(\n svc,\n 'UpdateParticipant',\n req.toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * Updates a participant's subscription to tracks\n * @param room -\n * @param identity -\n * @param trackSids -\n * @param subscribe - true to subscribe, false to unsubscribe\n */\n async updateSubscriptions(\n room: string,\n identity: string,\n trackSids: string[],\n subscribe: boolean,\n ): Promise<void> {\n const req = new UpdateSubscriptionsRequest({\n room,\n identity,\n trackSids,\n subscribe,\n participantTracks: [],\n }).toJson();\n await this.rpc.request(\n svc,\n 'UpdateSubscriptions',\n req,\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Sends data message to participants in the room\n * @param room -\n * @param data - opaque payload to send\n * @param kind - delivery reliability\n * @param options - optionally specify a topic and destinationSids (when destinationSids is empty, message is sent to everyone)\n */\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n options: SendDataOptions,\n ): Promise<void>;\n /**\n * Sends data message to participants in the room\n * @deprecated use sendData(room, data, kind, options) instead\n * @param room -\n * @param data - opaque payload to send\n * @param kind - delivery reliability\n * @param destinationSids - optional. when empty, message is sent to everyone\n */\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n destinationSids?: string[],\n ): Promise<void>;\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n options: SendDataOptions | string[] = {},\n ): Promise<void> {\n const destinationSids = Array.isArray(options) ? options : options.destinationSids;\n const topic = Array.isArray(options) ? undefined : options.topic;\n const req = new SendDataRequest({\n room,\n data,\n kind,\n destinationSids: destinationSids ?? [],\n topic,\n });\n if (!Array.isArray(options) && options.destinationIdentities) {\n req.destinationIdentities = options.destinationIdentities;\n }\n req.nonce = await getRandomBytes(16);\n await this.rpc.request(\n svc,\n 'SendData',\n req.toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,sBAkBO;AACP,yBAA4B;AAE5B,sBAAyC;AACzC,kBAA+B;AA6E/B,MAAM,MAAM;AAKL,MAAM,0BAA0B,+BAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASjD,YAAY,MAAc,QAAiB,QAAiB;AAC1D,UAAM,QAAQ,MAAM;AACpB,SAAK,MAAM,IAAI,yBAAS,MAAM,8BAAc;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA;AAAA;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A,MACA;AAAA,MACA,mBAAmB,CAAC;AAAA,IACtB,CAAC,EAAE,OAAO;AACV,UAAM,KAAK,IAAI;AAAA,MACb;AAAA,MACA;AAAA,MACA;AAAA,MACA,MAAM,KAAK,WAAW,EAAE,WAAW,MAAM,KAAK,CAAC;AAAA,IACjD;AAAA,EACF;AAAA,EA6BA,MAAM,SACJ,MACA,MACA,MACA,UAAsC,CAAC,GACxB;AACf,UAAM,kBAAkB,MAAM,QAAQ,OAAO,IAAI,UAAU,QAAQ;AACnE,UAAM,QAAQ,MAAM,QAAQ,OAAO,IAAI,SAAY,QAAQ;AAC3D,UAAM,MAAM,IAAI,gCAAgB;AAAA,MAC9B;AAAA,MACA;AAAA,MACA;AAAA,MACA,iBAAiB,mBAAmB,CAAC;AAAA,MACrC;AAAA,IACF,CAAC;AACD,QAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,uBAAuB;AAC5D,UAAI,wBAAwB,QAAQ;AAAA,IACtC;AACA,QAAI,QAAQ,UAAM,4BAAe,EAAE;AACnC,UAAM,KAAK,IAAI;AAAA,MACb;AAAA,MACA;AAAA,MACA,IAAI,OAAO;AAAA,MACX,MAAM,KAAK,WAAW,EAAE,WAAW,MAAM,KAAK,CAAC;AAAA,IACjD;AAAA,EACF;AACF;","names":[]}
@@ -121,6 +121,16 @@ declare class RoomServiceClient extends ServiceBase {
121
121
  * @param identity -
122
122
  */
123
123
  removeParticipant(room: string, identity: string): Promise<void>;
124
+ /**
125
+ * Forwards a participant's track to another room. This will create a
126
+ * participant to join the destination room that has same information
127
+ * with the source participant except the kind to be `Forwarded`. All
128
+ * changes to the source participant will be reflected to the forwarded
129
+ * participant. When the source participant disconnects or the
130
+ * `RemoveParticipant` method is called in the destination room, the
131
+ * forwarding will be stopped.
132
+ */
133
+ forwardParticipant(room: string, identity: string, destinationRoom: string): Promise<void>;
124
134
  /**
125
135
  * Mutes a track that the participant has published.
126
136
  * @param room -
@@ -119,6 +119,16 @@ export declare class RoomServiceClient extends ServiceBase {
119
119
  * @param identity -
120
120
  */
121
121
  removeParticipant(room: string, identity: string): Promise<void>;
122
+ /**
123
+ * Forwards a participant's track to another room. This will create a
124
+ * participant to join the destination room that has same information
125
+ * with the source participant except the kind to be `Forwarded`. All
126
+ * changes to the source participant will be reflected to the forwarded
127
+ * participant. When the source participant disconnects or the
128
+ * `RemoveParticipant` method is called in the destination room, the
129
+ * forwarding will be stopped.
130
+ */
131
+ forwardParticipant(room: string, identity: string, destinationRoom: string): Promise<void>;
122
132
  /**
123
133
  * Mutes a track that the participant has published.
124
134
  * @param room -
@@ -1 +1 @@
1
- {"version":3,"file":"RoomServiceClient.d.ts","sourceRoot":"","sources":["../src/RoomServiceClient.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAChF,OAAO,EASL,eAAe,EACf,qBAAqB,EACrB,IAAI,EAML,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAK/C;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,MAAM,CAAC,EAAE,UAAU,CAAC;IAEpB;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,MAAM,eAAe,GAAG;IA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EAAE,MAAM,EAChB,QAAQ,CAAC,EAAE,MAAM,EACjB,UAAU,CAAC,EAAE,OAAO,CAAC,qBAAqB,CAAC,EAC3C,IAAI,CAAC,EAAE,MAAM,GACZ,OAAO,CAAC,eAAe,CAAC;IAmC3B;;;;;;OAMG;IACG,mBAAmB,CACvB,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EAAE,EACnB,SAAS,EAAE,OAAO,GACjB,OAAO,CAAC,IAAI,CAAC;IAgBhB;;;;;;OAMG;IACG,QAAQ,CACZ,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,UAAU,EAChB,IAAI,EAAE,eAAe,EACrB,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,IAAI,CAAC;IAChB;;;;;;;OAOG;IACG,QAAQ,CACZ,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,UAAU,EAChB,IAAI,EAAE,eAAe,EACrB,eAAe,CAAC,EAAE,MAAM,EAAE,GACzB,OAAO,CAAC,IAAI,CAAC;CA2BjB"}
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  CreateRoomRequest,
3
3
  DeleteRoomRequest,
4
+ ForwardParticipantRequest,
4
5
  ListParticipantsRequest,
5
6
  ListParticipantsResponse,
6
7
  ListRoomsRequest,
@@ -128,6 +129,23 @@ class RoomServiceClient extends ServiceBase {
128
129
  await this.authHeader({ roomAdmin: true, room })
129
130
  );
130
131
  }
132
+ /**
133
+ * Forwards a participant's track to another room. This will create a
134
+ * participant to join the destination room that has same information
135
+ * with the source participant except the kind to be `Forwarded`. All
136
+ * changes to the source participant will be reflected to the forwarded
137
+ * participant. When the source participant disconnects or the
138
+ * `RemoveParticipant` method is called in the destination room, the
139
+ * forwarding will be stopped.
140
+ */
141
+ async forwardParticipant(room, identity, destinationRoom) {
142
+ await this.rpc.request(
143
+ svc,
144
+ "ForwardParticipant",
145
+ new ForwardParticipantRequest({ room, identity, destinationRoom }).toJson(),
146
+ await this.authHeader({ roomAdmin: true, room })
147
+ );
148
+ }
131
149
  /**
132
150
  * Mutes a track that the participant has published.
133
151
  * @param room -
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/RoomServiceClient.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { DataPacket_Kind, RoomEgress, TrackInfo } from '@livekit/protocol';\nimport {\n CreateRoomRequest,\n DeleteRoomRequest,\n ListParticipantsRequest,\n ListParticipantsResponse,\n ListRoomsRequest,\n ListRoomsResponse,\n MuteRoomTrackRequest,\n MuteRoomTrackResponse,\n ParticipantInfo,\n ParticipantPermission,\n Room,\n RoomParticipantIdentity,\n SendDataRequest,\n UpdateParticipantRequest,\n UpdateRoomMetadataRequest,\n UpdateSubscriptionsRequest,\n} from '@livekit/protocol';\nimport { ServiceBase } from './ServiceBase.js';\nimport type { Rpc } from './TwirpRPC.js';\nimport { TwirpRpc, livekitPackage } from './TwirpRPC.js';\nimport { getRandomBytes } from './crypto/uuid.js';\n\n/**\n * Options for when creating a room\n */\nexport interface CreateOptions {\n /**\n * name of the room. required\n */\n name: string;\n\n /**\n * number of seconds to keep the room open before any participant joins\n */\n emptyTimeout?: number;\n\n /**\n * number of seconds to keep the room open after the last participant leaves\n * this option is helpful to give a grace period for participants to re-join\n */\n departureTimeout?: number;\n\n /**\n * limit to the number of participants in a room at a time\n */\n maxParticipants?: number;\n\n /**\n * initial room metadata\n */\n metadata?: string;\n\n /**\n * add egress options\n */\n egress?: RoomEgress;\n\n /**\n * minimum playout delay in milliseconds\n */\n minPlayoutDelay?: number;\n\n /**\n * maximum playout delay in milliseconds\n */\n maxPlayoutDelay?: number;\n\n /**\n * improves A/V sync when min_playout_delay set to a value larger than 200ms.\n * It will disables transceiver re-use -- this option is not recommended\n * for rooms with frequent subscription changes\n */\n syncStreams?: boolean;\n\n /**\n * override the node room is allocated to, for debugging\n * does not work with Cloud\n */\n nodeId?: string;\n}\n\nexport type SendDataOptions = {\n /** If set, only deliver to listed participant identities */\n destinationIdentities?: string[];\n destinationSids?: string[];\n topic?: string;\n};\n\nexport type UpdateParticipantOptions = {\n /** only attributes you'd want to update should be set, set value to empty string to remove it */\n attributes?: { [key: string]: string };\n metadata?: string;\n /** permissions are updated atomically - all desired permissions would need to be set */\n permission?: Partial<ParticipantPermission>;\n name?: string;\n};\n\nconst svc = 'RoomService';\n\n/**\n * Client to access Room APIs\n */\nexport class RoomServiceClient extends ServiceBase {\n private readonly rpc: Rpc;\n\n /**\n *\n * @param host - hostname including protocol. i.e. 'https://<project>.livekit.cloud'\n * @param apiKey - API Key, can be set in env var LIVEKIT_API_KEY\n * @param secret - API Secret, can be set in env var LIVEKIT_API_SECRET\n */\n constructor(host: string, apiKey?: string, secret?: string) {\n super(apiKey, secret);\n this.rpc = new TwirpRpc(host, livekitPackage);\n }\n\n /**\n * Creates a new room. Explicit room creation is not required, since rooms will\n * be automatically created when the first participant joins. This method can be\n * used to customize room settings.\n * @param options -\n */\n async createRoom(options: CreateOptions): Promise<Room> {\n const data = await this.rpc.request(\n svc,\n 'CreateRoom',\n new CreateRoomRequest(options).toJson(),\n await this.authHeader({ roomCreate: true }),\n );\n return Room.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * List active rooms\n * @param names - when undefined or empty, list all rooms.\n * otherwise returns rooms with matching names\n * @returns\n */\n async listRooms(names?: string[]): Promise<Room[]> {\n const data = await this.rpc.request(\n svc,\n 'ListRooms',\n new ListRoomsRequest({ names: names ?? [] }).toJson(),\n await this.authHeader({ roomList: true }),\n );\n const res = ListRoomsResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.rooms ?? [];\n }\n\n async deleteRoom(room: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'DeleteRoom',\n new DeleteRoomRequest({ room }).toJson(),\n await this.authHeader({ roomCreate: true }),\n );\n }\n\n /**\n * Update metadata of a room\n * @param room - name of the room\n * @param metadata - the new metadata for the room\n */\n async updateRoomMetadata(room: string, metadata: string) {\n const data = await this.rpc.request(\n svc,\n 'UpdateRoomMetadata',\n new UpdateRoomMetadataRequest({ room, metadata }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n return Room.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * List participants in a room\n * @param room - name of the room\n */\n async listParticipants(room: string): Promise<ParticipantInfo[]> {\n const data = await this.rpc.request(\n svc,\n 'ListParticipants',\n new ListParticipantsRequest({ room }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n const res = ListParticipantsResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.participants ?? [];\n }\n\n /**\n * Get information on a specific participant, including the tracks that participant\n * has published\n * @param room - name of the room\n * @param identity - identity of the participant to return\n */\n async getParticipant(room: string, identity: string): Promise<ParticipantInfo> {\n const data = await this.rpc.request(\n svc,\n 'GetParticipant',\n new RoomParticipantIdentity({ room, identity }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n\n return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * Removes a participant in the room. This will disconnect the participant\n * and will emit a Disconnected event for that participant.\n * Even after being removed, the participant can still re-join the room.\n * @param room -\n * @param identity -\n */\n async removeParticipant(room: string, identity: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'RemoveParticipant',\n new RoomParticipantIdentity({ room, identity }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Mutes a track that the participant has published.\n * @param room -\n * @param identity -\n * @param trackSid - sid of the track to be muted\n * @param muted - true to mute, false to unmute\n */\n async mutePublishedTrack(\n room: string,\n identity: string,\n trackSid: string,\n muted: boolean,\n ): Promise<TrackInfo> {\n const req = new MuteRoomTrackRequest({\n room,\n identity,\n trackSid,\n muted,\n }).toJson();\n const data = await this.rpc.request(\n svc,\n 'MutePublishedTrack',\n req,\n await this.authHeader({ roomAdmin: true, room }),\n );\n const res = MuteRoomTrackResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.track!;\n }\n\n /**\n * Updates a participant's state or permissions\n * @param room - target room\n * @param identity - participant identity\n * @param options - participant fields to update\n */\n async updateParticipant(\n room: string,\n identity: string,\n options: UpdateParticipantOptions,\n ): Promise<ParticipantInfo>;\n /**\n * Updates a participant's state or permissions\n * @param room - target room\n * @param identity - participant identity\n * @param options - participant fields to update\n */\n async updateParticipant(\n room: string,\n identity: string,\n metadata?: string,\n permission?: Partial<ParticipantPermission>,\n name?: string,\n ): Promise<ParticipantInfo>;\n async updateParticipant(\n room: string,\n identity: string,\n metadataOrOptions?: string | UpdateParticipantOptions,\n maybePermission?: Partial<ParticipantPermission>,\n maybeName?: string,\n ): Promise<ParticipantInfo> {\n const hasOptions = typeof metadataOrOptions === 'object';\n const metadata = hasOptions ? metadataOrOptions?.metadata : metadataOrOptions;\n const permission = hasOptions ? metadataOrOptions.permission : maybePermission;\n const name = hasOptions ? metadataOrOptions.name : maybeName;\n const attributes: Record<string, string> | undefined = hasOptions\n ? metadataOrOptions.attributes\n : {};\n\n const req = new UpdateParticipantRequest({\n room,\n identity,\n attributes,\n metadata,\n name,\n });\n if (permission) {\n req.permission = new ParticipantPermission(permission);\n }\n const data = await this.rpc.request(\n svc,\n 'UpdateParticipant',\n req.toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * Updates a participant's subscription to tracks\n * @param room -\n * @param identity -\n * @param trackSids -\n * @param subscribe - true to subscribe, false to unsubscribe\n */\n async updateSubscriptions(\n room: string,\n identity: string,\n trackSids: string[],\n subscribe: boolean,\n ): Promise<void> {\n const req = new UpdateSubscriptionsRequest({\n room,\n identity,\n trackSids,\n subscribe,\n participantTracks: [],\n }).toJson();\n await this.rpc.request(\n svc,\n 'UpdateSubscriptions',\n req,\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Sends data message to participants in the room\n * @param room -\n * @param data - opaque payload to send\n * @param kind - delivery reliability\n * @param options - optionally specify a topic and destinationSids (when destinationSids is empty, message is sent to everyone)\n */\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n options: SendDataOptions,\n ): Promise<void>;\n /**\n * Sends data message to participants in the room\n * @deprecated use sendData(room, data, kind, options) instead\n * @param room -\n * @param data - opaque payload to send\n * @param kind - delivery reliability\n * @param destinationSids - optional. when empty, message is sent to everyone\n */\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n destinationSids?: string[],\n ): Promise<void>;\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n options: SendDataOptions | string[] = {},\n ): Promise<void> {\n const destinationSids = Array.isArray(options) ? options : options.destinationSids;\n const topic = Array.isArray(options) ? undefined : options.topic;\n const req = new SendDataRequest({\n room,\n data,\n kind,\n destinationSids: destinationSids ?? [],\n topic,\n });\n if (!Array.isArray(options) && options.destinationIdentities) {\n req.destinationIdentities = options.destinationIdentities;\n }\n req.nonce = await getRandomBytes(16);\n await this.rpc.request(\n svc,\n 'SendData',\n req.toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n}\n"],"mappings":"AAIA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAE5B,SAAS,UAAU,sBAAsB;AACzC,SAAS,sBAAsB;AA6E/B,MAAM,MAAM;AAKL,MAAM,0BAA0B,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASjD,YAAY,MAAc,QAAiB,QAAiB;AAC1D,UAAM,QAAQ,MAAM;AACpB,SAAK,MAAM,IAAI,SAAS,MAAM,cAAc;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,WAA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,MAAM,QAAQ,OAAO,IAAI,SAAY,QAAQ;AAC3D,UAAM,MAAM,IAAI,gBAAgB;AAAA,MAC9B;AAAA,MACA;AAAA,MACA;AAAA,MACA,iBAAiB,mBAAmB,CAAC;AAAA,MACrC;AAAA,IACF,CAAC;AACD,QAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,uBAAuB;AAC5D,UAAI,wBAAwB,QAAQ;AAAA,IACtC;AACA,QAAI,QAAQ,MAAM,eAAe,EAAE;AACnC,UAAM,KAAK,IAAI;AAAA,MACb;AAAA,MACA;AAAA,MACA,IAAI,OAAO;AAAA,MACX,MAAM,KAAK,WAAW,EAAE,WAAW,MAAM,KAAK,CAAC;AAAA,IACjD;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/RoomServiceClient.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { DataPacket_Kind, RoomEgress, TrackInfo } from '@livekit/protocol';\nimport {\n CreateRoomRequest,\n DeleteRoomRequest,\n ForwardParticipantRequest,\n ListParticipantsRequest,\n ListParticipantsResponse,\n ListRoomsRequest,\n ListRoomsResponse,\n MuteRoomTrackRequest,\n MuteRoomTrackResponse,\n ParticipantInfo,\n ParticipantPermission,\n Room,\n RoomParticipantIdentity,\n SendDataRequest,\n UpdateParticipantRequest,\n UpdateRoomMetadataRequest,\n UpdateSubscriptionsRequest,\n} from '@livekit/protocol';\nimport { ServiceBase } from './ServiceBase.js';\nimport type { Rpc } from './TwirpRPC.js';\nimport { TwirpRpc, livekitPackage } from './TwirpRPC.js';\nimport { getRandomBytes } from './crypto/uuid.js';\n\n/**\n * Options for when creating a room\n */\nexport interface CreateOptions {\n /**\n * name of the room. required\n */\n name: string;\n\n /**\n * number of seconds to keep the room open before any participant joins\n */\n emptyTimeout?: number;\n\n /**\n * number of seconds to keep the room open after the last participant leaves\n * this option is helpful to give a grace period for participants to re-join\n */\n departureTimeout?: number;\n\n /**\n * limit to the number of participants in a room at a time\n */\n maxParticipants?: number;\n\n /**\n * initial room metadata\n */\n metadata?: string;\n\n /**\n * add egress options\n */\n egress?: RoomEgress;\n\n /**\n * minimum playout delay in milliseconds\n */\n minPlayoutDelay?: number;\n\n /**\n * maximum playout delay in milliseconds\n */\n maxPlayoutDelay?: number;\n\n /**\n * improves A/V sync when min_playout_delay set to a value larger than 200ms.\n * It will disables transceiver re-use -- this option is not recommended\n * for rooms with frequent subscription changes\n */\n syncStreams?: boolean;\n\n /**\n * override the node room is allocated to, for debugging\n * does not work with Cloud\n */\n nodeId?: string;\n}\n\nexport type SendDataOptions = {\n /** If set, only deliver to listed participant identities */\n destinationIdentities?: string[];\n destinationSids?: string[];\n topic?: string;\n};\n\nexport type UpdateParticipantOptions = {\n /** only attributes you'd want to update should be set, set value to empty string to remove it */\n attributes?: { [key: string]: string };\n metadata?: string;\n /** permissions are updated atomically - all desired permissions would need to be set */\n permission?: Partial<ParticipantPermission>;\n name?: string;\n};\n\nconst svc = 'RoomService';\n\n/**\n * Client to access Room APIs\n */\nexport class RoomServiceClient extends ServiceBase {\n private readonly rpc: Rpc;\n\n /**\n *\n * @param host - hostname including protocol. i.e. 'https://<project>.livekit.cloud'\n * @param apiKey - API Key, can be set in env var LIVEKIT_API_KEY\n * @param secret - API Secret, can be set in env var LIVEKIT_API_SECRET\n */\n constructor(host: string, apiKey?: string, secret?: string) {\n super(apiKey, secret);\n this.rpc = new TwirpRpc(host, livekitPackage);\n }\n\n /**\n * Creates a new room. Explicit room creation is not required, since rooms will\n * be automatically created when the first participant joins. This method can be\n * used to customize room settings.\n * @param options -\n */\n async createRoom(options: CreateOptions): Promise<Room> {\n const data = await this.rpc.request(\n svc,\n 'CreateRoom',\n new CreateRoomRequest(options).toJson(),\n await this.authHeader({ roomCreate: true }),\n );\n return Room.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * List active rooms\n * @param names - when undefined or empty, list all rooms.\n * otherwise returns rooms with matching names\n * @returns\n */\n async listRooms(names?: string[]): Promise<Room[]> {\n const data = await this.rpc.request(\n svc,\n 'ListRooms',\n new ListRoomsRequest({ names: names ?? [] }).toJson(),\n await this.authHeader({ roomList: true }),\n );\n const res = ListRoomsResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.rooms ?? [];\n }\n\n async deleteRoom(room: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'DeleteRoom',\n new DeleteRoomRequest({ room }).toJson(),\n await this.authHeader({ roomCreate: true }),\n );\n }\n\n /**\n * Update metadata of a room\n * @param room - name of the room\n * @param metadata - the new metadata for the room\n */\n async updateRoomMetadata(room: string, metadata: string) {\n const data = await this.rpc.request(\n svc,\n 'UpdateRoomMetadata',\n new UpdateRoomMetadataRequest({ room, metadata }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n return Room.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * List participants in a room\n * @param room - name of the room\n */\n async listParticipants(room: string): Promise<ParticipantInfo[]> {\n const data = await this.rpc.request(\n svc,\n 'ListParticipants',\n new ListParticipantsRequest({ room }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n const res = ListParticipantsResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.participants ?? [];\n }\n\n /**\n * Get information on a specific participant, including the tracks that participant\n * has published\n * @param room - name of the room\n * @param identity - identity of the participant to return\n */\n async getParticipant(room: string, identity: string): Promise<ParticipantInfo> {\n const data = await this.rpc.request(\n svc,\n 'GetParticipant',\n new RoomParticipantIdentity({ room, identity }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n\n return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * Removes a participant in the room. This will disconnect the participant\n * and will emit a Disconnected event for that participant.\n * Even after being removed, the participant can still re-join the room.\n * @param room -\n * @param identity -\n */\n async removeParticipant(room: string, identity: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'RemoveParticipant',\n new RoomParticipantIdentity({ room, identity }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Forwards a participant's track to another room. This will create a\n * participant to join the destination room that has same information\n * with the source participant except the kind to be `Forwarded`. All\n * changes to the source participant will be reflected to the forwarded\n * participant. When the source participant disconnects or the\n * `RemoveParticipant` method is called in the destination room, the\n * forwarding will be stopped.\n */\n async forwardParticipant(room: string, identity: string, destinationRoom: string): Promise<void> {\n await this.rpc.request(\n svc,\n 'ForwardParticipant',\n new ForwardParticipantRequest({ room, identity, destinationRoom }).toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Mutes a track that the participant has published.\n * @param room -\n * @param identity -\n * @param trackSid - sid of the track to be muted\n * @param muted - true to mute, false to unmute\n */\n async mutePublishedTrack(\n room: string,\n identity: string,\n trackSid: string,\n muted: boolean,\n ): Promise<TrackInfo> {\n const req = new MuteRoomTrackRequest({\n room,\n identity,\n trackSid,\n muted,\n }).toJson();\n const data = await this.rpc.request(\n svc,\n 'MutePublishedTrack',\n req,\n await this.authHeader({ roomAdmin: true, room }),\n );\n const res = MuteRoomTrackResponse.fromJson(data, { ignoreUnknownFields: true });\n return res.track!;\n }\n\n /**\n * Updates a participant's state or permissions\n * @param room - target room\n * @param identity - participant identity\n * @param options - participant fields to update\n */\n async updateParticipant(\n room: string,\n identity: string,\n options: UpdateParticipantOptions,\n ): Promise<ParticipantInfo>;\n /**\n * Updates a participant's state or permissions\n * @param room - target room\n * @param identity - participant identity\n * @param options - participant fields to update\n */\n async updateParticipant(\n room: string,\n identity: string,\n metadata?: string,\n permission?: Partial<ParticipantPermission>,\n name?: string,\n ): Promise<ParticipantInfo>;\n async updateParticipant(\n room: string,\n identity: string,\n metadataOrOptions?: string | UpdateParticipantOptions,\n maybePermission?: Partial<ParticipantPermission>,\n maybeName?: string,\n ): Promise<ParticipantInfo> {\n const hasOptions = typeof metadataOrOptions === 'object';\n const metadata = hasOptions ? metadataOrOptions?.metadata : metadataOrOptions;\n const permission = hasOptions ? metadataOrOptions.permission : maybePermission;\n const name = hasOptions ? metadataOrOptions.name : maybeName;\n const attributes: Record<string, string> | undefined = hasOptions\n ? metadataOrOptions.attributes\n : {};\n\n const req = new UpdateParticipantRequest({\n room,\n identity,\n attributes,\n metadata,\n name,\n });\n if (permission) {\n req.permission = new ParticipantPermission(permission);\n }\n const data = await this.rpc.request(\n svc,\n 'UpdateParticipant',\n req.toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });\n }\n\n /**\n * Updates a participant's subscription to tracks\n * @param room -\n * @param identity -\n * @param trackSids -\n * @param subscribe - true to subscribe, false to unsubscribe\n */\n async updateSubscriptions(\n room: string,\n identity: string,\n trackSids: string[],\n subscribe: boolean,\n ): Promise<void> {\n const req = new UpdateSubscriptionsRequest({\n room,\n identity,\n trackSids,\n subscribe,\n participantTracks: [],\n }).toJson();\n await this.rpc.request(\n svc,\n 'UpdateSubscriptions',\n req,\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n\n /**\n * Sends data message to participants in the room\n * @param room -\n * @param data - opaque payload to send\n * @param kind - delivery reliability\n * @param options - optionally specify a topic and destinationSids (when destinationSids is empty, message is sent to everyone)\n */\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n options: SendDataOptions,\n ): Promise<void>;\n /**\n * Sends data message to participants in the room\n * @deprecated use sendData(room, data, kind, options) instead\n * @param room -\n * @param data - opaque payload to send\n * @param kind - delivery reliability\n * @param destinationSids - optional. when empty, message is sent to everyone\n */\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n destinationSids?: string[],\n ): Promise<void>;\n async sendData(\n room: string,\n data: Uint8Array,\n kind: DataPacket_Kind,\n options: SendDataOptions | string[] = {},\n ): Promise<void> {\n const destinationSids = Array.isArray(options) ? options : options.destinationSids;\n const topic = Array.isArray(options) ? undefined : options.topic;\n const req = new SendDataRequest({\n room,\n data,\n kind,\n destinationSids: destinationSids ?? [],\n topic,\n });\n if (!Array.isArray(options) && options.destinationIdentities) {\n req.destinationIdentities = options.destinationIdentities;\n }\n req.nonce = await getRandomBytes(16);\n await this.rpc.request(\n svc,\n 'SendData',\n req.toJson(),\n await this.authHeader({ roomAdmin: true, room }),\n );\n }\n}\n"],"mappings":"AAIA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAE5B,SAAS,UAAU,sBAAsB;AACzC,SAAS,sBAAsB;AA6E/B,MAAM,MAAM;AAKL,MAAM,0BAA0B,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASjD,YAAY,MAAc,QAAiB,QAAiB;AAC1D,UAAM,QAAQ,MAAM;AACpB,SAAK,MAAM,IAAI,SAAS,MAAM,cAAc;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,WAAW,SAAuC;AACtD,UAAM,OAAO,MAAM,KAAK,IAAI;AAAA,MAC1B;AAAA,MACA;AAAA,MACA,IAAI,kBAAkB,OAAO,EAAE,OAAO;AAAA,MACtC,MAAM,KAAK,WAAW,EAAE,YAAY,KAAK,CAAC;AAAA,IAC5C;AACA,WAAO,KAAK,SAAS,MAAM,EAAE,qBAAqB,KAAK,CAAC;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,UAAU,OAAmC;AACjD,UAAM,OAAO,MAAM,KAAK,IAAI;AAAA,MAC1B;AAAA,MACA;AAAA,MACA,IAAI,iBAAiB,EAAE,OAAO,SAAS,CAAC,EAAE,CAAC,EAAE,OAAO;AAAA,MACpD,MAAM,KAAK,WAAW,EAAE,UAAU,KAAK,CAAC;A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OAAO,KAAK,QAAQ,uBAAuB;AAC5D,UAAI,wBAAwB,QAAQ;AAAA,IACtC;AACA,QAAI,QAAQ,MAAM,eAAe,EAAE;AACnC,UAAM,KAAK,IAAI;AAAA,MACb;AAAA,MACA;AAAA,MACA,IAAI,OAAO;AAAA,MACX,MAAM,KAAK,WAAW,EAAE,WAAW,MAAM,KAAK,CAAC;AAAA,IACjD;AAAA,EACF;AACF;","names":[]}
@@ -50,14 +50,15 @@ class WebhookReceiver {
50
50
  * @param body - string of the posted body
51
51
  * @param authHeader - `Authorization` header from the request
52
52
  * @param skipAuth - true to skip auth validation
53
- * @returns
53
+ * @param clockTolerance - How much tolerance to allow for checks against the auth header to be skewed from the claims
54
+ * @returns The processed webhook event
54
55
  */
55
- async receive(body, authHeader, skipAuth = false) {
56
+ async receive(body, authHeader, skipAuth = false, clockTolerance) {
56
57
  if (!skipAuth) {
57
58
  if (!authHeader) {
58
59
  throw new Error("authorization header is empty");
59
60
  }
60
- const claims = await this.verifier.verify(authHeader);
61
+ const claims = await this.verifier.verify(authHeader, clockTolerance);
61
62
  const hash = await (0, import_digest.digest)(body);
62
63
  const hashDecoded = btoa(
63
64
  Array.from(new Uint8Array(hash)).map((v) => String.fromCharCode(v)).join("")
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/WebhookReceiver.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { BinaryReadOptions, JsonReadOptions, JsonValue } from '@bufbuild/protobuf';\nimport { WebhookEvent as ProtoWebhookEvent } from '@livekit/protocol';\nimport { TokenVerifier } from './AccessToken.js';\nimport { digest } from './crypto/digest.js';\n\nexport const authorizeHeader = 'Authorize';\n\nexport class WebhookEvent extends ProtoWebhookEvent {\n event: WebhookEventNames = '';\n\n static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): WebhookEvent {\n return new WebhookEvent().fromBinary(bytes, options);\n }\n\n static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): WebhookEvent {\n return new WebhookEvent().fromJson(jsonValue, options);\n }\n\n static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): WebhookEvent {\n return new WebhookEvent().fromJsonString(jsonString, options);\n }\n}\n\nexport type WebhookEventNames =\n | 'room_started'\n | 'room_finished'\n | 'participant_joined'\n | 'participant_left'\n | 'track_published'\n | 'track_unpublished'\n | 'egress_started'\n | 'egress_updated'\n | 'egress_ended'\n | 'ingress_started'\n | 'ingress_ended'\n /**\n * @internal\n * @remarks only used as a default value, not a valid webhook event\n */\n | '';\n\nexport class WebhookReceiver {\n private verifier: TokenVerifier;\n\n constructor(apiKey: string, apiSecret: string) {\n this.verifier = new TokenVerifier(apiKey, apiSecret);\n }\n\n /**\n * @param body - string of the posted body\n * @param authHeader - `Authorization` header from the request\n * @param skipAuth - true to skip auth validation\n * @returns\n */\n async receive(\n body: string,\n authHeader?: string,\n skipAuth: boolean = false,\n ): Promise<WebhookEvent> {\n // verify token\n if (!skipAuth) {\n if (!authHeader) {\n throw new Error('authorization header is empty');\n }\n const claims = await this.verifier.verify(authHeader);\n // confirm sha\n const hash = await digest(body);\n const hashDecoded = btoa(\n Array.from(new Uint8Array(hash))\n .map((v) => String.fromCharCode(v))\n .join(''),\n );\n\n if (claims.sha256 !== hashDecoded) {\n throw new Error('sha256 checksum of body does not match');\n }\n }\n\n return WebhookEvent.fromJson(JSON.parse(body), { ignoreUnknownFields: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,sBAAkD;AAClD,yBAA8B;AAC9B,oBAAuB;AAEhB,MAAM,kBAAkB;AAExB,MAAM,qBAAqB,gBAAAA,aAAkB;AAAA,EAA7C;AAAA;AACL,iBAA2B;AAAA;AAAA,EAE3B,OAAO,WAAW,OAAmB,SAAoD;AACvF,WAAO,IAAI,aAAa,EAAE,WAAW,OAAO,OAAO;AAAA,EACrD;AAAA,EAEA,OAAO,SAAS,WAAsB,SAAkD;AACtF,WAAO,IAAI,aAAa,EAAE,SAAS,WAAW,OAAO;AAAA,EACvD;AAAA,EAEA,OAAO,eAAe,YAAoB,SAAkD;AAC1F,WAAO,IAAI,aAAa,EAAE,eAAe,YAAY,OAAO;AAAA,EAC9D;AACF;AAoBO,MAAM,gBAAgB;AAAA,EAG3B,YAAY,QAAgB,WAAmB;AAC7C,SAAK,WAAW,IAAI,iCAAc,QAAQ,SAAS;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,QACJ,MACA,YACA,WAAoB,OACG;AAEvB,QAAI,CAAC,UAAU;AACb,UAAI,CAAC,YAAY;AACf,cAAM,IAAI,MAAM,+BAA+B;AAAA,MACjD;AACA,YAAM,SAAS,MAAM,KAAK,SAAS,OAAO,UAAU;AAEpD,YAAM,OAAO,UAAM,sBAAO,IAAI;AAC9B,YAAM,cAAc;AAAA,QAClB,MAAM,KAAK,IAAI,WAAW,IAAI,CAAC,EAC5B,IAAI,CAAC,MAAM,OAAO,aAAa,CAAC,CAAC,EACjC,KAAK,EAAE;AAAA,MACZ;AAEA,UAAI,OAAO,WAAW,aAAa;AACjC,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAAA,IACF;AAEA,WAAO,aAAa,SAAS,KAAK,MAAM,IAAI,GAAG,EAAE,qBAAqB,KAAK,CAAC;AAAA,EAC9E;AACF;","names":["ProtoWebhookEvent"]}
1
+ {"version":3,"sources":["../src/WebhookReceiver.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { BinaryReadOptions, JsonReadOptions, JsonValue } from '@bufbuild/protobuf';\nimport { WebhookEvent as ProtoWebhookEvent } from '@livekit/protocol';\nimport { TokenVerifier } from './AccessToken.js';\nimport { digest } from './crypto/digest.js';\n\nexport const authorizeHeader = 'Authorize';\n\nexport class WebhookEvent extends ProtoWebhookEvent {\n event: WebhookEventNames = '';\n\n static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): WebhookEvent {\n return new WebhookEvent().fromBinary(bytes, options);\n }\n\n static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): WebhookEvent {\n return new WebhookEvent().fromJson(jsonValue, options);\n }\n\n static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): WebhookEvent {\n return new WebhookEvent().fromJsonString(jsonString, options);\n }\n}\n\nexport type WebhookEventNames =\n | 'room_started'\n | 'room_finished'\n | 'participant_joined'\n | 'participant_left'\n | 'track_published'\n | 'track_unpublished'\n | 'egress_started'\n | 'egress_updated'\n | 'egress_ended'\n | 'ingress_started'\n | 'ingress_ended'\n /**\n * @internal\n * @remarks only used as a default value, not a valid webhook event\n */\n | '';\n\nexport class WebhookReceiver {\n private verifier: TokenVerifier;\n\n constructor(apiKey: string, apiSecret: string) {\n this.verifier = new TokenVerifier(apiKey, apiSecret);\n }\n\n /**\n * @param body - string of the posted body\n * @param authHeader - `Authorization` header from the request\n * @param skipAuth - true to skip auth validation\n * @param clockTolerance - How much tolerance to allow for checks against the auth header to be skewed from the claims\n * @returns The processed webhook event\n */\n async receive(\n body: string,\n authHeader?: string,\n skipAuth: boolean = false,\n clockTolerance?: string | number,\n ): Promise<WebhookEvent> {\n // verify token\n if (!skipAuth) {\n if (!authHeader) {\n throw new Error('authorization header is empty');\n }\n const claims = await this.verifier.verify(authHeader, clockTolerance);\n // confirm sha\n const hash = await digest(body);\n const hashDecoded = btoa(\n Array.from(new Uint8Array(hash))\n .map((v) => String.fromCharCode(v))\n .join(''),\n );\n\n if (claims.sha256 !== hashDecoded) {\n throw new Error('sha256 checksum of body does not match');\n }\n }\n\n return WebhookEvent.fromJson(JSON.parse(body), { ignoreUnknownFields: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,sBAAkD;AAClD,yBAA8B;AAC9B,oBAAuB;AAEhB,MAAM,kBAAkB;AAExB,MAAM,qBAAqB,gBAAAA,aAAkB;AAAA,EAA7C;AAAA;AACL,iBAA2B;AAAA;AAAA,EAE3B,OAAO,WAAW,OAAmB,SAAoD;AACvF,WAAO,IAAI,aAAa,EAAE,WAAW,OAAO,OAAO;AAAA,EACrD;AAAA,EAEA,OAAO,SAAS,WAAsB,SAAkD;AACtF,WAAO,IAAI,aAAa,EAAE,SAAS,WAAW,OAAO;AAAA,EACvD;AAAA,EAEA,OAAO,eAAe,YAAoB,SAAkD;AAC1F,WAAO,IAAI,aAAa,EAAE,eAAe,YAAY,OAAO;AAAA,EAC9D;AACF;AAoBO,MAAM,gBAAgB;AAAA,EAG3B,YAAY,QAAgB,WAAmB;AAC7C,SAAK,WAAW,IAAI,iCAAc,QAAQ,SAAS;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,QACJ,MACA,YACA,WAAoB,OACpB,gBACuB;AAEvB,QAAI,CAAC,UAAU;AACb,UAAI,CAAC,YAAY;AACf,cAAM,IAAI,MAAM,+BAA+B;AAAA,MACjD;AACA,YAAM,SAAS,MAAM,KAAK,SAAS,OAAO,YAAY,cAAc;AAEpE,YAAM,OAAO,UAAM,sBAAO,IAAI;AAC9B,YAAM,cAAc;AAAA,QAClB,MAAM,KAAK,IAAI,WAAW,IAAI,CAAC,EAC5B,IAAI,CAAC,MAAM,OAAO,aAAa,CAAC,CAAC,EACjC,KAAK,EAAE;AAAA,MACZ;AAEA,UAAI,OAAO,WAAW,aAAa;AACjC,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAAA,IACF;AAEA,WAAO,aAAa,SAAS,KAAK,MAAM,IAAI,GAAG,EAAE,qBAAqB,KAAK,CAAC;AAAA,EAC9E;AACF;","names":["ProtoWebhookEvent"]}
@@ -21,9 +21,10 @@ declare class WebhookReceiver {
21
21
  * @param body - string of the posted body
22
22
  * @param authHeader - `Authorization` header from the request
23
23
  * @param skipAuth - true to skip auth validation
24
- * @returns
24
+ * @param clockTolerance - How much tolerance to allow for checks against the auth header to be skewed from the claims
25
+ * @returns The processed webhook event
25
26
  */
26
- receive(body: string, authHeader?: string, skipAuth?: boolean): Promise<WebhookEvent>;
27
+ receive(body: string, authHeader?: string, skipAuth?: boolean, clockTolerance?: string | number): Promise<WebhookEvent>;
27
28
  }
28
29
 
29
30
  export { WebhookEvent, type WebhookEventNames, WebhookReceiver, authorizeHeader };
@@ -20,8 +20,9 @@ export declare class WebhookReceiver {
20
20
  * @param body - string of the posted body
21
21
  * @param authHeader - `Authorization` header from the request
22
22
  * @param skipAuth - true to skip auth validation
23
- * @returns
23
+ * @param clockTolerance - How much tolerance to allow for checks against the auth header to be skewed from the claims
24
+ * @returns The processed webhook event
24
25
  */
25
- receive(body: string, authHeader?: string, skipAuth?: boolean): Promise<WebhookEvent>;
26
+ receive(body: string, authHeader?: string, skipAuth?: boolean, clockTolerance?: string | number): Promise<WebhookEvent>;
26
27
  }
27
28
  //# sourceMappingURL=WebhookReceiver.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"WebhookReceiver.d.ts","sourceRoot":"","sources":["../src/WebhookReceiver.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACxF,OAAO,EAAE,YAAY,IAAI,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAItE,eAAO,MAAM,eAAe,cAAc,CAAC;AAE3C,qBAAa,YAAa,SAAQ,iBAAiB;IACjD,KAAK,EAAE,iBAAiB,CAAM;IAE9B,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,GAAG,YAAY;IAIxF,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,eAAe,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AAe,CAAC,GAAG,YAAY;CAG5F;AAED,MAAM,MAAM,iBAAiB,GACzB,cAAc,GACd,eAAe,GACf,oBAAoB,GACpB,kBAAkB,GAClB,iBAAiB,GACjB,mBAAmB,GACnB,gBAAgB,GAChB,gBAAgB,GAChB,cAAc,GACd,iBAAiB,GACjB,eAAe;AACjB;;;GAGG;GACD,EAAE,CAAC;AAEP,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAgB;gBAEpB,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;IAI7C;;;;;;OAMG;IACG,OAAO,CACX,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,MAAM,EACnB,QAAQ,GAAE,OAAe,EACzB,cAAc,CAAC,EAAE,MAAM,GAAG,MAAM,GAC/B,OAAO,CAAC,YAAY,CAAC;CAsBzB"}
@@ -25,14 +25,15 @@ class WebhookReceiver {
25
25
  * @param body - string of the posted body
26
26
  * @param authHeader - `Authorization` header from the request
27
27
  * @param skipAuth - true to skip auth validation
28
- * @returns
28
+ * @param clockTolerance - How much tolerance to allow for checks against the auth header to be skewed from the claims
29
+ * @returns The processed webhook event
29
30
  */
30
- async receive(body, authHeader, skipAuth = false) {
31
+ async receive(body, authHeader, skipAuth = false, clockTolerance) {
31
32
  if (!skipAuth) {
32
33
  if (!authHeader) {
33
34
  throw new Error("authorization header is empty");
34
35
  }
35
- const claims = await this.verifier.verify(authHeader);
36
+ const claims = await this.verifier.verify(authHeader, clockTolerance);
36
37
  const hash = await digest(body);
37
38
  const hashDecoded = btoa(
38
39
  Array.from(new Uint8Array(hash)).map((v) => String.fromCharCode(v)).join("")
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/WebhookReceiver.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { BinaryReadOptions, JsonReadOptions, JsonValue } from '@bufbuild/protobuf';\nimport { WebhookEvent as ProtoWebhookEvent } from '@livekit/protocol';\nimport { TokenVerifier } from './AccessToken.js';\nimport { digest } from './crypto/digest.js';\n\nexport const authorizeHeader = 'Authorize';\n\nexport class WebhookEvent extends ProtoWebhookEvent {\n event: WebhookEventNames = '';\n\n static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): WebhookEvent {\n return new WebhookEvent().fromBinary(bytes, options);\n }\n\n static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): WebhookEvent {\n return new WebhookEvent().fromJson(jsonValue, options);\n }\n\n static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): WebhookEvent {\n return new WebhookEvent().fromJsonString(jsonString, options);\n }\n}\n\nexport type WebhookEventNames =\n | 'room_started'\n | 'room_finished'\n | 'participant_joined'\n | 'participant_left'\n | 'track_published'\n | 'track_unpublished'\n | 'egress_started'\n | 'egress_updated'\n | 'egress_ended'\n | 'ingress_started'\n | 'ingress_ended'\n /**\n * @internal\n * @remarks only used as a default value, not a valid webhook event\n */\n | '';\n\nexport class WebhookReceiver {\n private verifier: TokenVerifier;\n\n constructor(apiKey: string, apiSecret: string) {\n this.verifier = new TokenVerifier(apiKey, apiSecret);\n }\n\n /**\n * @param body - string of the posted body\n * @param authHeader - `Authorization` header from the request\n * @param skipAuth - true to skip auth validation\n * @returns\n */\n async receive(\n body: string,\n authHeader?: string,\n skipAuth: boolean = false,\n ): Promise<WebhookEvent> {\n // verify token\n if (!skipAuth) {\n if (!authHeader) {\n throw new Error('authorization header is empty');\n }\n const claims = await this.verifier.verify(authHeader);\n // confirm sha\n const hash = await digest(body);\n const hashDecoded = btoa(\n Array.from(new Uint8Array(hash))\n .map((v) => String.fromCharCode(v))\n .join(''),\n );\n\n if (claims.sha256 !== hashDecoded) {\n throw new Error('sha256 checksum of body does not match');\n }\n }\n\n return WebhookEvent.fromJson(JSON.parse(body), { ignoreUnknownFields: true });\n }\n}\n"],"mappings":"AAIA,SAAS,gBAAgB,yBAAyB;AAClD,SAAS,qBAAqB;AAC9B,SAAS,cAAc;AAEhB,MAAM,kBAAkB;AAExB,MAAM,qBAAqB,kBAAkB;AAAA,EAA7C;AAAA;AACL,iBAA2B;AAAA;AAAA,EAE3B,OAAO,WAAW,OAAmB,SAAoD;AACvF,WAAO,IAAI,aAAa,EAAE,WAAW,OAAO,OAAO;AAAA,EACrD;AAAA,EAEA,OAAO,SAAS,WAAsB,SAAkD;AACtF,WAAO,IAAI,aAAa,EAAE,SAAS,WAAW,OAAO;AAAA,EACvD;AAAA,EAEA,OAAO,eAAe,YAAoB,SAAkD;AAC1F,WAAO,IAAI,aAAa,EAAE,eAAe,YAAY,OAAO;AAAA,EAC9D;AACF;AAoBO,MAAM,gBAAgB;AAAA,EAG3B,YAAY,QAAgB,WAAmB;AAC7C,SAAK,WAAW,IAAI,cAAc,QAAQ,SAAS;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,QACJ,MACA,YACA,WAAoB,OACG;AAEvB,QAAI,CAAC,UAAU;AACb,UAAI,CAAC,YAAY;AACf,cAAM,IAAI,MAAM,+BAA+B;AAAA,MACjD;AACA,YAAM,SAAS,MAAM,KAAK,SAAS,OAAO,UAAU;AAEpD,YAAM,OAAO,MAAM,OAAO,IAAI;AAC9B,YAAM,cAAc;AAAA,QAClB,MAAM,KAAK,IAAI,WAAW,IAAI,CAAC,EAC5B,IAAI,CAAC,MAAM,OAAO,aAAa,CAAC,CAAC,EACjC,KAAK,EAAE;AAAA,MACZ;AAEA,UAAI,OAAO,WAAW,aAAa;AACjC,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAAA,IACF;AAEA,WAAO,aAAa,SAAS,KAAK,MAAM,IAAI,GAAG,EAAE,qBAAqB,KAAK,CAAC;AAAA,EAC9E;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/WebhookReceiver.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { BinaryReadOptions, JsonReadOptions, JsonValue } from '@bufbuild/protobuf';\nimport { WebhookEvent as ProtoWebhookEvent } from '@livekit/protocol';\nimport { TokenVerifier } from './AccessToken.js';\nimport { digest } from './crypto/digest.js';\n\nexport const authorizeHeader = 'Authorize';\n\nexport class WebhookEvent extends ProtoWebhookEvent {\n event: WebhookEventNames = '';\n\n static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): WebhookEvent {\n return new WebhookEvent().fromBinary(bytes, options);\n }\n\n static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): WebhookEvent {\n return new WebhookEvent().fromJson(jsonValue, options);\n }\n\n static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): WebhookEvent {\n return new WebhookEvent().fromJsonString(jsonString, options);\n }\n}\n\nexport type WebhookEventNames =\n | 'room_started'\n | 'room_finished'\n | 'participant_joined'\n | 'participant_left'\n | 'track_published'\n | 'track_unpublished'\n | 'egress_started'\n | 'egress_updated'\n | 'egress_ended'\n | 'ingress_started'\n | 'ingress_ended'\n /**\n * @internal\n * @remarks only used as a default value, not a valid webhook event\n */\n | '';\n\nexport class WebhookReceiver {\n private verifier: TokenVerifier;\n\n constructor(apiKey: string, apiSecret: string) {\n this.verifier = new TokenVerifier(apiKey, apiSecret);\n }\n\n /**\n * @param body - string of the posted body\n * @param authHeader - `Authorization` header from the request\n * @param skipAuth - true to skip auth validation\n * @param clockTolerance - How much tolerance to allow for checks against the auth header to be skewed from the claims\n * @returns The processed webhook event\n */\n async receive(\n body: string,\n authHeader?: string,\n skipAuth: boolean = false,\n clockTolerance?: string | number,\n ): Promise<WebhookEvent> {\n // verify token\n if (!skipAuth) {\n if (!authHeader) {\n throw new Error('authorization header is empty');\n }\n const claims = await this.verifier.verify(authHeader, clockTolerance);\n // confirm sha\n const hash = await digest(body);\n const hashDecoded = btoa(\n Array.from(new Uint8Array(hash))\n .map((v) => String.fromCharCode(v))\n .join(''),\n );\n\n if (claims.sha256 !== hashDecoded) {\n throw new Error('sha256 checksum of body does not match');\n }\n }\n\n return WebhookEvent.fromJson(JSON.parse(body), { ignoreUnknownFields: true });\n }\n}\n"],"mappings":"AAIA,SAAS,gBAAgB,yBAAyB;AAClD,SAAS,qBAAqB;AAC9B,SAAS,cAAc;AAEhB,MAAM,kBAAkB;AAExB,MAAM,qBAAqB,kBAAkB;AAAA,EAA7C;AAAA;AACL,iBAA2B;AAAA;AAAA,EAE3B,OAAO,WAAW,OAAmB,SAAoD;AACvF,WAAO,IAAI,aAAa,EAAE,WAAW,OAAO,OAAO;AAAA,EACrD;AAAA,EAEA,OAAO,SAAS,WAAsB,SAAkD;AACtF,WAAO,IAAI,aAAa,EAAE,SAAS,WAAW,OAAO;AAAA,EACvD;AAAA,EAEA,OAAO,eAAe,YAAoB,SAAkD;AAC1F,WAAO,IAAI,aAAa,EAAE,eAAe,YAAY,OAAO;AAAA,EAC9D;AACF;AAoBO,MAAM,gBAAgB;AAAA,EAG3B,YAAY,QAAgB,WAAmB;AAC7C,SAAK,WAAW,IAAI,cAAc,QAAQ,SAAS;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,QACJ,MACA,YACA,WAAoB,OACpB,gBACuB;AAEvB,QAAI,CAAC,UAAU;AACb,UAAI,CAAC,YAAY;AACf,cAAM,IAAI,MAAM,+BAA+B;AAAA,MACjD;AACA,YAAM,SAAS,MAAM,KAAK,SAAS,OAAO,YAAY,cAAc;AAEpE,YAAM,OAAO,MAAM,OAAO,IAAI;AAC9B,YAAM,cAAc;AAAA,QAClB,MAAM,KAAK,IAAI,WAAW,IAAI,CAAC,EAC5B,IAAI,CAAC,MAAM,OAAO,aAAa,CAAC,CAAC,EACjC,KAAK,EAAE;AAAA,MACZ;AAEA,UAAI,OAAO,WAAW,aAAa;AACjC,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAAA,IACF;AAEA,WAAO,aAAa,SAAS,KAAK,MAAM,IAAI,GAAG,EAAE,qBAAqB,KAAK,CAAC;AAAA,EAC9E;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "livekit-server-sdk",
3
- "version": "2.10.2",
3
+ "version": "2.11.0",
4
4
  "description": "Server-side SDK for LiveKit",
5
5
  "main": "dist/index.js",
6
6
  "require": "dist/index.cjs",
@@ -30,7 +30,7 @@
30
30
  ],
31
31
  "dependencies": {
32
32
  "@bufbuild/protobuf": "^1.7.2",
33
- "@livekit/protocol": "^1.32.1",
33
+ "@livekit/protocol": "^1.36.1",
34
34
  "camelcase-keys": "^9.0.0",
35
35
  "jose": "^5.1.2"
36
36
  },
@@ -9,6 +9,8 @@ import { claimsToJwtPayload } from './grants.js';
9
9
  // 6 hours
10
10
  const defaultTTL = `6h`;
11
11
 
12
+ const defaultClockToleranceSeconds = 10;
13
+
12
14
  export interface AccessTokenOptions {
13
15
  /**
14
16
  * amount of time before expiration
@@ -199,9 +201,15 @@ export class TokenVerifier {
199
201
  this.apiSecret = apiSecret;
200
202
  }
201
203
 
202
- async verify(token: string): Promise<ClaimGrants> {
204
+ async verify(
205
+ token: string,
206
+ clockTolerance: string | number = defaultClockToleranceSeconds,
207
+ ): Promise<ClaimGrants> {
203
208
  const secret = new TextEncoder().encode(this.apiSecret);
204
- const { payload } = await jose.jwtVerify(token, secret, { issuer: this.apiKey });
209
+ const { payload } = await jose.jwtVerify(token, secret, {
210
+ issuer: this.apiKey,
211
+ clockTolerance,
212
+ });
205
213
  if (!payload) {
206
214
  throw Error('invalid token');
207
215
  }
@@ -5,6 +5,7 @@ import type { DataPacket_Kind, RoomEgress, TrackInfo } from '@livekit/protocol';
5
5
  import {
6
6
  CreateRoomRequest,
7
7
  DeleteRoomRequest,
8
+ ForwardParticipantRequest,
8
9
  ListParticipantsRequest,
9
10
  ListParticipantsResponse,
10
11
  ListRoomsRequest,
@@ -224,6 +225,24 @@ export class RoomServiceClient extends ServiceBase {
224
225
  );
225
226
  }
226
227
 
228
+ /**
229
+ * Forwards a participant's track to another room. This will create a
230
+ * participant to join the destination room that has same information
231
+ * with the source participant except the kind to be `Forwarded`. All
232
+ * changes to the source participant will be reflected to the forwarded
233
+ * participant. When the source participant disconnects or the
234
+ * `RemoveParticipant` method is called in the destination room, the
235
+ * forwarding will be stopped.
236
+ */
237
+ async forwardParticipant(room: string, identity: string, destinationRoom: string): Promise<void> {
238
+ await this.rpc.request(
239
+ svc,
240
+ 'ForwardParticipant',
241
+ new ForwardParticipantRequest({ room, identity, destinationRoom }).toJson(),
242
+ await this.authHeader({ roomAdmin: true, room }),
243
+ );
244
+ }
245
+
227
246
  /**
228
247
  * Mutes a track that the participant has published.
229
248
  * @param room -
@@ -53,19 +53,21 @@ export class WebhookReceiver {
53
53
  * @param body - string of the posted body
54
54
  * @param authHeader - `Authorization` header from the request
55
55
  * @param skipAuth - true to skip auth validation
56
- * @returns
56
+ * @param clockTolerance - How much tolerance to allow for checks against the auth header to be skewed from the claims
57
+ * @returns The processed webhook event
57
58
  */
58
59
  async receive(
59
60
  body: string,
60
61
  authHeader?: string,
61
62
  skipAuth: boolean = false,
63
+ clockTolerance?: string | number,
62
64
  ): Promise<WebhookEvent> {
63
65
  // verify token
64
66
  if (!skipAuth) {
65
67
  if (!authHeader) {
66
68
  throw new Error('authorization header is empty');
67
69
  }
68
- const claims = await this.verifier.verify(authHeader);
70
+ const claims = await this.verifier.verify(authHeader, clockTolerance);
69
71
  // confirm sha
70
72
  const hash = await digest(body);
71
73
  const hashDecoded = btoa(