@ethora/sdk-backend 25.12.15

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.
@@ -0,0 +1,389 @@
1
+ "use strict";
2
+ /**
3
+ * Concrete implementation of the ChatRepository using the Ethora API
4
+ *
5
+ * This class handles chat operations in the Ethora chat service. It manages
6
+ * JWT authentication tokens for server-to-server communication and uses
7
+ * HTTP clients to make asynchronous API calls.
8
+ *
9
+ * @format
10
+ */
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.EthoraSDKService = void 0;
16
+ exports.getEthoraSDKService = getEthoraSDKService;
17
+ const crypto_1 = require("crypto");
18
+ const axios_1 = __importDefault(require("axios"));
19
+ const secrets_1 = require("../config/secrets");
20
+ const jwt_1 = require("../utils/jwt");
21
+ const logger_1 = require("../utils/logger");
22
+ const logger = (0, logger_1.getLogger)("EthoraSDKService");
23
+ /**
24
+ * EthoraSDKService - Concrete implementation of ChatRepository
25
+ */
26
+ class EthoraSDKService {
27
+ constructor() {
28
+ this.secrets = (0, secrets_1.getSecrets)();
29
+ this.baseEthoraUrl = this.secrets.chatApiUrl;
30
+ // Create axios instance with default configuration
31
+ this.httpClient = axios_1.default.create({
32
+ timeout: secrets_1.DEFAULT_TIMEOUT.total,
33
+ headers: {
34
+ "Content-Type": "application/json",
35
+ },
36
+ });
37
+ logger.debug("EthoraSDKService instance initialized");
38
+ }
39
+ /**
40
+ * Generates a fully-qualified chat room JID from a workspace ID
41
+ *
42
+ * The JID is constructed in the format `<appId>_<workspace_id>@conference.xmpp.ethoradev.com`.
43
+ * This method uses a static JID domain to provide a unique identifier for a chat room.
44
+ *
45
+ * @param workspaceId - The unique identifier of the workspace
46
+ * @param full - Whether to include the full JID domain
47
+ * @returns The fully-qualified JID string for the chat room
48
+ */
49
+ createChatName(workspaceId, full = true) {
50
+ logger.debug(`Creating chat room name (JID) for workspace ID: ${workspaceId}`);
51
+ const chatName = full
52
+ ? `${this.secrets.chatAppId}_${workspaceId}${secrets_1.ETHORA_JID_DOMAIN}`
53
+ : `${this.secrets.chatAppId}_${workspaceId}`;
54
+ logger.info(`Chat room name created: '${chatName}'`);
55
+ return chatName;
56
+ }
57
+ /**
58
+ * Creates a client-side JWT token for a specific user ID
59
+ *
60
+ * This method generates a JWT token for a user that can be used for client-side
61
+ * authentication with the chat service. The token payload includes the
62
+ * user's ID and the app ID.
63
+ *
64
+ * @param userId - The unique identifier of the user
65
+ * @returns The encoded JWT token for client-side authentication
66
+ */
67
+ createChatUserJwtToken(userId) {
68
+ logger.debug(`Creating a client-side JWT token for user ID: ${userId}`);
69
+ return (0, jwt_1.createClientToken)(userId);
70
+ }
71
+ /**
72
+ * Creates the necessary headers for an API call with a JWT token
73
+ *
74
+ * @returns The headers dictionary containing the `x-custom-token` field
75
+ */
76
+ getHeaders() {
77
+ logger.debug("Retrieving headers for a server-to-server API call");
78
+ return {
79
+ "x-custom-token": (0, jwt_1.createServerToken)(),
80
+ };
81
+ }
82
+ /**
83
+ * Makes an HTTP request with error handling
84
+ *
85
+ * @param config - Axios request configuration
86
+ * @returns The API response
87
+ */
88
+ async makeRequest(config) {
89
+ try {
90
+ const response = await this.httpClient.request({
91
+ ...config,
92
+ headers: {
93
+ ...this.getHeaders(),
94
+ ...config.headers,
95
+ },
96
+ timeout: secrets_1.DEFAULT_TIMEOUT.total,
97
+ });
98
+ return response.data;
99
+ }
100
+ catch (error) {
101
+ if (axios_1.default.isAxiosError(error)) {
102
+ const axiosError = error;
103
+ logger.error(`API call failed with status code: ${axiosError.response?.status}. ` +
104
+ `Response: ${axiosError.response?.data}`, error);
105
+ throw error;
106
+ }
107
+ logger.error("An unexpected error occurred during API call", error);
108
+ throw error;
109
+ }
110
+ }
111
+ /**
112
+ * Creates a user in the chat service
113
+ *
114
+ * Uses the batch API endpoint to create a single user. The API expects:
115
+ * - bypassEmailConfirmation: true
116
+ * - usersList: array with user objects containing email, firstName, lastName, password, uuid
117
+ *
118
+ * @param userId - The unique identifier of the user (used as uuid)
119
+ * @param userData - Additional user data (optional) - can include email, firstName, lastName, password, etc.
120
+ * @returns The API response
121
+ */
122
+ async createUser(userId, userData) {
123
+ logger.info(`Attempting to create user with ID: ${userId}`);
124
+ const createUrl = `${this.baseEthoraUrl}/v1/users/batch`;
125
+ // Extract user fields from userData or use defaults
126
+ // Generate unique email using UUID if not provided
127
+ const email = userData?.email || `${(0, crypto_1.randomUUID)()}@example.com`;
128
+ const password = userData?.password || `password_${userId}`;
129
+ // Handle firstName and lastName - split displayName if provided
130
+ // API requires lastName to be at least 2 characters and not empty
131
+ let firstName;
132
+ let lastName;
133
+ if (userData?.firstName) {
134
+ firstName = userData.firstName;
135
+ lastName = userData?.lastName || "";
136
+ }
137
+ else if (userData?.displayName) {
138
+ const displayName = userData.displayName;
139
+ const nameParts = displayName.trim().split(/\s+/);
140
+ firstName = nameParts[0] || "User";
141
+ lastName = nameParts.slice(1).join(" ") || "";
142
+ }
143
+ else {
144
+ firstName = "User";
145
+ lastName = "";
146
+ }
147
+ // Ensure lastName meets API requirements: at least 2 characters, not empty
148
+ if (!lastName || lastName.length < 2) {
149
+ // Use a default lastName if empty or too short
150
+ lastName = "User";
151
+ }
152
+ // API requires uuid to start with appId for grant access to work
153
+ // Prefix userId with appId if it doesn't already start with it
154
+ const userIdStr = String(userId);
155
+ const prefixedUserId = userIdStr.startsWith(this.secrets.chatAppId)
156
+ ? userIdStr
157
+ : `${this.secrets.chatAppId}_${userIdStr}`;
158
+ const payload = {
159
+ bypassEmailConfirmation: true,
160
+ usersList: [
161
+ {
162
+ uuid: prefixedUserId,
163
+ email: email,
164
+ firstName: firstName,
165
+ lastName: lastName,
166
+ password: password,
167
+ ...(userData &&
168
+ Object.fromEntries(Object.entries(userData).filter(([key]) => ![
169
+ "email",
170
+ "firstName",
171
+ "lastName",
172
+ "password",
173
+ "uuid",
174
+ "displayName",
175
+ "role", // Role is not allowed in user creation payload
176
+ ].includes(key)))),
177
+ },
178
+ ],
179
+ };
180
+ logger.debug(`Chat service API URL: ${createUrl}`);
181
+ logger.debug(`Request payload: ${JSON.stringify(payload)}`);
182
+ return this.makeRequest({
183
+ method: "POST",
184
+ url: createUrl,
185
+ data: payload,
186
+ });
187
+ }
188
+ /**
189
+ * Creates a chat room for a workspace
190
+ *
191
+ * @param workspaceId - The unique identifier of the workspace
192
+ * @param roomData - Additional room data (optional)
193
+ * @returns The API response
194
+ */
195
+ async createChatRoom(workspaceId, roomData) {
196
+ logger.info(`Attempting to create chat room for workspace ID: ${workspaceId}`);
197
+ const createUrl = `${this.baseEthoraUrl}/v1/chats`;
198
+ // Create chat room - API expects title, uuid, and type
199
+ const payload = {
200
+ title: roomData?.title || `Chat Room ${workspaceId}`,
201
+ uuid: String(workspaceId),
202
+ type: roomData?.type || "group",
203
+ ...roomData, // Allow roomData to override fields if provided
204
+ };
205
+ logger.debug(`Chat service API URL: ${createUrl}`);
206
+ logger.debug(`Request payload: ${JSON.stringify(payload)}`);
207
+ return this.makeRequest({
208
+ method: "POST",
209
+ url: createUrl,
210
+ data: payload,
211
+ });
212
+ }
213
+ /**
214
+ * Normalizes a user ID to XMPP username format (appId_userId)
215
+ * This ensures consistency with how users are created in the system
216
+ *
217
+ * @param userId - The user ID to normalize
218
+ * @returns The XMPP username in format appId_userId
219
+ */
220
+ normalizeToXmppUsername(userId) {
221
+ const userIdStr = String(userId);
222
+ // If userId already starts with appId, use it as-is
223
+ // Otherwise, prefix it with appId to match the format used during user creation
224
+ if (userIdStr.startsWith(this.secrets.chatAppId)) {
225
+ return userIdStr;
226
+ }
227
+ return `${this.secrets.chatAppId}_${userIdStr}`;
228
+ }
229
+ /**
230
+ * Grants a user access to a chat room
231
+ *
232
+ * The API expects XMPP usernames in the format: appId_userId
233
+ * This matches the UUID format used when creating users (uuid: appId_userId)
234
+ *
235
+ * @param workspaceId - The unique identifier of the workspace
236
+ * @param userId - The unique identifier of the user (or array of user IDs)
237
+ * @returns The API response
238
+ */
239
+ async grantUserAccessToChatRoom(workspaceId, userId) {
240
+ logger.info(`Granting user(s) access to chat room for workspace ${workspaceId}`);
241
+ const chatName = this.createChatName(workspaceId, false);
242
+ // Use /v1/chats/users-access endpoint with chatName and members array
243
+ const grantUrl = `${this.baseEthoraUrl}/v1/chats/users-access`;
244
+ // Convert single userId to array if needed
245
+ // Normalize to XMPP username format (appId_userId) to match user creation format
246
+ const members = Array.isArray(userId)
247
+ ? userId.map((id) => this.normalizeToXmppUsername(id))
248
+ : [this.normalizeToXmppUsername(userId)];
249
+ const payload = {
250
+ chatName: chatName,
251
+ members: members,
252
+ };
253
+ logger.debug(`Chat service API URL: ${grantUrl}`);
254
+ logger.debug(`Request payload: ${JSON.stringify(payload)}`);
255
+ logger.debug(`Using XMPP usernames for members: ${members.join(", ")}`);
256
+ try {
257
+ return await this.makeRequest({
258
+ method: "POST",
259
+ url: grantUrl,
260
+ data: payload,
261
+ });
262
+ }
263
+ catch (error) {
264
+ if (axios_1.default.isAxiosError(error)) {
265
+ const errorData = error.response?.data;
266
+ logger.error(`Failed to grant user access. Status: ${error.response?.status}, Response: ${JSON.stringify(errorData)}`, error);
267
+ // Log the XMPP usernames that were attempted for debugging
268
+ logger.debug(`Attempted XMPP usernames: ${members.join(", ")}`);
269
+ }
270
+ throw error;
271
+ }
272
+ }
273
+ /**
274
+ * Grants chatbot access to a chat room
275
+ *
276
+ * @param workspaceId - The unique identifier of the workspace
277
+ * @returns The API response
278
+ */
279
+ async grantChatbotAccessToChatRoom(workspaceId) {
280
+ logger.info(`Granting chatbot access to chat room for workspace ${workspaceId}`);
281
+ if (!this.secrets.chatBotJid) {
282
+ const error = new Error("Chatbot JID not configured. Set ETHORA_CHAT_BOT_JID environment variable.");
283
+ logger.error("Cannot grant chatbot access", error);
284
+ throw error;
285
+ }
286
+ // Extract username from JID (format: "username@domain" -> "username")
287
+ const chatbotUsername = this.secrets.chatBotJid.split("@")[0];
288
+ // Use the same grant access method with chatbot JID
289
+ return this.grantUserAccessToChatRoom(workspaceId, chatbotUsername);
290
+ }
291
+ /**
292
+ * Deletes users from the chat service
293
+ *
294
+ * @param userIds - Array of user IDs to delete
295
+ * @returns The API response
296
+ */
297
+ async deleteUsers(userIds) {
298
+ logger.info(`Attempting to delete users: ${userIds.join(", ")}`);
299
+ const deleteUrl = `${this.baseEthoraUrl}/v1/users/batch`;
300
+ const payload = {
301
+ usersIdList: userIds.map((id) => String(id)),
302
+ };
303
+ logger.debug(`Chat service API URL: ${deleteUrl}`);
304
+ logger.debug(`Request payload: ${JSON.stringify(payload)}`);
305
+ try {
306
+ return await this.makeRequest({
307
+ method: "DELETE",
308
+ url: deleteUrl,
309
+ data: payload,
310
+ });
311
+ }
312
+ catch (error) {
313
+ // Handle the case where users don't exist (422 with "not found")
314
+ if (axios_1.default.isAxiosError(error) &&
315
+ error.response?.status === 422 &&
316
+ typeof error.response.data === "string" &&
317
+ error.response.data.includes("not found")) {
318
+ logger.info("No users to delete from the chat service. The request contained non-existent users.");
319
+ return { ok: false };
320
+ }
321
+ throw error;
322
+ }
323
+ }
324
+ /**
325
+ * Deletes a chat room from the chat service by its workspace ID
326
+ *
327
+ * This method sends a DELETE request to the Ethora API using the workspace ID
328
+ * to construct the chat name. It gracefully handles the case where the chat room
329
+ * is already non-existent (422 Not Found).
330
+ *
331
+ * @param workspaceId - The unique identifier of the workspace associated with the chat room
332
+ * @returns The JSON response from the chat service upon successful deletion or a success status if not found
333
+ */
334
+ async deleteChatRoom(workspaceId) {
335
+ logger.info(`Attempting to delete chat room for workspace ID: ${workspaceId}`);
336
+ const deleteUrl = `${this.baseEthoraUrl}/v1/chats`;
337
+ // We must use the short name when deleting the chat room
338
+ const chatName = this.createChatName(workspaceId, false);
339
+ const payload = {
340
+ name: chatName,
341
+ };
342
+ logger.debug(`Chat service API URL: ${deleteUrl}`);
343
+ logger.debug(`Request payload: ${JSON.stringify(payload)}`);
344
+ try {
345
+ const response = await this.makeRequest({
346
+ method: "DELETE",
347
+ url: deleteUrl,
348
+ data: payload,
349
+ });
350
+ logger.info(`Chat room '${chatName}' successfully deleted`);
351
+ return response;
352
+ }
353
+ catch (error) {
354
+ if (axios_1.default.isAxiosError(error)) {
355
+ const axiosError = error;
356
+ const statusCode = axiosError.response?.status;
357
+ const responseText = axiosError.response?.data;
358
+ // Handle the case where the room does not exist (Ethora returns 422 with "not found" in body)
359
+ if (statusCode === 422 &&
360
+ typeof responseText === "string" &&
361
+ responseText.toLowerCase().includes("not found")) {
362
+ logger.warn(`Chat room '${chatName}' not found during deletion attempt (Ignored 422)`);
363
+ return { ok: false, reason: "Chat room not found" };
364
+ }
365
+ }
366
+ // Re-throw if it's not a "not found" case
367
+ throw error;
368
+ }
369
+ }
370
+ }
371
+ exports.EthoraSDKService = EthoraSDKService;
372
+ /**
373
+ * Provides a singleton instance of EthoraSDKService
374
+ *
375
+ * This dependency injection function is intended for use with a DI framework
376
+ * or as a simple factory function. It creates and returns a single instance
377
+ * of `EthoraSDKService`.
378
+ *
379
+ * @returns A singleton instance of the chat repository implementation
380
+ */
381
+ let repositoryInstance = null;
382
+ function getEthoraSDKService() {
383
+ if (!repositoryInstance) {
384
+ logger.debug("Creating new EthoraSDKService instance");
385
+ repositoryInstance = new EthoraSDKService();
386
+ }
387
+ return repositoryInstance;
388
+ }
389
+ //# sourceMappingURL=EthoraSDKService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EthoraSDKService.js","sourceRoot":"","sources":["../../src/repositories/EthoraSDKService.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;;;AAkdH,kDAMC;AAtdD,mCAAoC;AACpC,kDAA6E;AAS7E,+CAI2B;AAC3B,sCAAoE;AACpE,4CAA4C;AAE5C,MAAM,MAAM,GAAG,IAAA,kBAAS,EAAC,kBAAkB,CAAC,CAAC;AAE7C;;GAEG;AACH,MAAa,gBAAgB;IAK3B;QAHiB,YAAO,GAAG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AAI,CAAC;AAEvD,SAAgB,mBAAmB;IACjC,IAAI,CAAC,kBAAkB,EAAE,CAAC;QACxB,MAAM,CAAC,KAAK,CAAC,wCAAwC,CAAC,CAAC;QACvD,kBAAkB,GAAG,IAAI,gBAAgB,EAAE,CAAC;IAC9C,CAAC;IACD,OAAO,kBAAkB,CAAC;AAC5B,CAAC"}
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Type definitions for the Ethora SDK
3
+ */
4
+ /**
5
+ * UUID type - can be a string or UUID object
6
+ */
7
+ export type UUID = string;
8
+ /**
9
+ * Chat room name format options
10
+ */
11
+ export interface ChatNameOptions {
12
+ /** Whether to include the full JID domain */
13
+ full?: boolean;
14
+ }
15
+ /**
16
+ * JWT token payload for server authentication
17
+ */
18
+ export interface ServerTokenPayload {
19
+ data: {
20
+ appId: string;
21
+ type: "server";
22
+ };
23
+ }
24
+ /**
25
+ * JWT token payload for client authentication
26
+ */
27
+ export interface ClientTokenPayload {
28
+ data: {
29
+ type: "client";
30
+ userId: string;
31
+ appId: string;
32
+ };
33
+ }
34
+ /**
35
+ * API response structure
36
+ */
37
+ export interface ApiResponse {
38
+ ok?: boolean;
39
+ reason?: string;
40
+ [key: string]: unknown;
41
+ }
42
+ /**
43
+ * Chat room creation request payload
44
+ */
45
+ export interface CreateChatRoomRequest {
46
+ title: string;
47
+ uuid: string;
48
+ type: string;
49
+ [key: string]: unknown;
50
+ }
51
+ /**
52
+ * Delete chat room request payload
53
+ */
54
+ export interface DeleteChatRoomRequest {
55
+ name: string;
56
+ }
57
+ /**
58
+ * Grant access request payload
59
+ */
60
+ export interface GrantAccessRequest {
61
+ chatName: string;
62
+ members: string[];
63
+ [key: string]: unknown;
64
+ }
65
+ /**
66
+ * Chat repository interface
67
+ */
68
+ export interface ChatRepository {
69
+ /**
70
+ * Creates a fully-qualified chat room JID from a workspace ID
71
+ */
72
+ createChatName(workspaceId: UUID, full?: boolean): string;
73
+ /**
74
+ * Creates a client-side JWT token for a specific user ID
75
+ */
76
+ createChatUserJwtToken(userId: UUID): string;
77
+ /**
78
+ * Creates a user in the chat service
79
+ */
80
+ createUser(userId: UUID, userData?: Record<string, unknown>): Promise<ApiResponse>;
81
+ /**
82
+ * Creates a chat room for a workspace
83
+ */
84
+ createChatRoom(workspaceId: UUID, roomData?: Record<string, unknown>): Promise<ApiResponse>;
85
+ /**
86
+ * Grants a user access to a chat room
87
+ */
88
+ grantUserAccessToChatRoom(workspaceId: UUID, userId: UUID | UUID[]): Promise<ApiResponse>;
89
+ /**
90
+ * Grants chatbot access to a chat room
91
+ */
92
+ grantChatbotAccessToChatRoom(workspaceId: UUID): Promise<ApiResponse>;
93
+ /**
94
+ * Deletes users from the chat service
95
+ */
96
+ deleteUsers(userIds: UUID[]): Promise<ApiResponse>;
97
+ /**
98
+ * Deletes a chat room by workspace ID
99
+ */
100
+ deleteChatRoom(workspaceId: UUID): Promise<ApiResponse>;
101
+ }
102
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;GAEG;AACH,MAAM,MAAM,IAAI,GAAG,MAAM,CAAC;AAE1B;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,6CAA6C;IAC7C,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE;QACJ,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,QAAQ,CAAC;KAChB,CAAC;CACH;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE;QACJ,IAAI,EAAE,QAAQ,CAAC;QACf,MAAM,EAAE,MAAM,CAAC;QACf,KAAK,EAAE,MAAM,CAAC;KACf,CAAC;CACH;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,EAAE,CAAC,EAAE,OAAO,CAAC;IACb,MAAM,CAAC,E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AAE,IAAI,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAEnD;;OAEG;IACH,cAAc,CAAC,WAAW,EAAE,IAAI,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;CACzD"}
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * Type definitions for the Ethora SDK
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":";AAAA;;GAEG"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * JWT token utilities for Ethora SDK
3
+ */
4
+ import jwt from "jsonwebtoken";
5
+ import type { ServerTokenPayload, ClientTokenPayload } from "../types";
6
+ /**
7
+ * Creates a JWT token from the given payload using the chat application's secret
8
+ *
9
+ * @param payload - The payload to be encoded in the JWT
10
+ * @returns The encoded JWT token
11
+ */
12
+ export declare function createJwtToken(payload: ServerTokenPayload | ClientTokenPayload): string;
13
+ /**
14
+ * Creates a server-to-server JWT token
15
+ *
16
+ * @returns The encoded JWT token for server authentication
17
+ */
18
+ export declare function createServerToken(): string;
19
+ /**
20
+ * Creates a client-side JWT token for a specific user ID
21
+ *
22
+ * @param userId - The unique identifier of the user
23
+ * @returns The encoded JWT token for client-side authentication
24
+ */
25
+ export declare function createClientToken(userId: string): string;
26
+ /**
27
+ * Verifies a JWT token
28
+ *
29
+ * @param token - The JWT token to verify
30
+ * @returns The decoded token payload
31
+ * @throws Error if token is invalid
32
+ */
33
+ export declare function verifyJwtToken(token: string): jwt.JwtPayload;
34
+ //# sourceMappingURL=jwt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["../../src/utils/jwt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,GAAG,MAAM,cAAc,CAAC;AAC/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAMvE;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,kBAAkB,GAAG,kBAAkB,GAAG,MAAM,CAWvF;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAY1C;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAexD;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAAC,UAAU,CAY5D"}
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ /**
3
+ * JWT token utilities for Ethora SDK
4
+ */
5
+ var __importDefault = (this && this.__importDefault) || function (mod) {
6
+ return (mod && mod.__esModule) ? mod : { "default": mod };
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.createJwtToken = createJwtToken;
10
+ exports.createServerToken = createServerToken;
11
+ exports.createClientToken = createClientToken;
12
+ exports.verifyJwtToken = verifyJwtToken;
13
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
14
+ const secrets_1 = require("../config/secrets");
15
+ const logger_1 = require("./logger");
16
+ const logger = (0, logger_1.getLogger)("jwt-utils");
17
+ /**
18
+ * Creates a JWT token from the given payload using the chat application's secret
19
+ *
20
+ * @param payload - The payload to be encoded in the JWT
21
+ * @returns The encoded JWT token
22
+ */
23
+ function createJwtToken(payload) {
24
+ logger.debug("Creating a new JWT token");
25
+ const secrets = (0, secrets_1.getSecrets)();
26
+ return jsonwebtoken_1.default.sign(payload, secrets.chatAppSecret, {
27
+ algorithm: "HS256",
28
+ });
29
+ }
30
+ /**
31
+ * Creates a server-to-server JWT token
32
+ *
33
+ * @returns The encoded JWT token for server authentication
34
+ */
35
+ function createServerToken() {
36
+ logger.debug("Creating server-to-server JWT token");
37
+ const secrets = (0, secrets_1.getSecrets)();
38
+ const payload = {
39
+ data: {
40
+ appId: secrets.chatAppId,
41
+ type: "server",
42
+ },
43
+ };
44
+ return createJwtToken(payload);
45
+ }
46
+ /**
47
+ * Creates a client-side JWT token for a specific user ID
48
+ *
49
+ * @param userId - The unique identifier of the user
50
+ * @returns The encoded JWT token for client-side authentication
51
+ */
52
+ function createClientToken(userId) {
53
+ logger.debug(`Creating a client-side JWT token for user ID: ${userId}`);
54
+ const secrets = (0, secrets_1.getSecrets)();
55
+ const payload = {
56
+ data: {
57
+ type: "client",
58
+ userId: String(userId),
59
+ appId: secrets.chatAppId,
60
+ },
61
+ };
62
+ const token = createJwtToken(payload);
63
+ logger.info(`Client JWT token created for user ID: ${userId}`);
64
+ return token;
65
+ }
66
+ /**
67
+ * Verifies a JWT token
68
+ *
69
+ * @param token - The JWT token to verify
70
+ * @returns The decoded token payload
71
+ * @throws Error if token is invalid
72
+ */
73
+ function verifyJwtToken(token) {
74
+ logger.debug("Verifying JWT token");
75
+ const secrets = (0, secrets_1.getSecrets)();
76
+ try {
77
+ return jsonwebtoken_1.default.verify(token, secrets.chatAppSecret, {
78
+ algorithms: ["HS256"],
79
+ });
80
+ }
81
+ catch (error) {
82
+ logger.error("JWT token verification failed", error);
83
+ throw new Error("Invalid JWT token");
84
+ }
85
+ }
86
+ //# sourceMappingURL=jwt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt.js","sourceRoot":"","sources":["../../src/utils/jwt.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;AAeH,wCAWC;AAOD,8CAYC;AAQD,8CAeC;AASD,wCAYC;AAvFD,gEAA+B;AAE/B,+CAA+C;AAC/C,qCAAqC;AAErC,MAAM,MAAM,GAAG,IAAA,kBAAS,EAAC,WAAW,CAAC,CAAC;AAEtC;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,OAAgD;IAC7E,MAAM,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;IACzC,MAAM,OAAO,GAAG,IAAA,oBAAU,GAAE,CAAC;IAE7B,OAAO,sBAAG,CAAC,IAAI,CACb,O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