-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateToken.js
More file actions
193 lines (173 loc) · 5.09 KB
/
Copy pathgenerateToken.js
File metadata and controls
193 lines (173 loc) · 5.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import chalk from "chalk";
import dotenv from "dotenv";
import KJUR from "jsrsasign";
import clipboardy from "clipboardy";
import { Command } from "commander";
import { GoogleGenAI } from "@google/genai";
dotenv.config({ quiet: true });
const program = new Command();
const sdkKey = process.env.ZOOM_SDK_KEY;
const sdkSecret = process.env.ZOOM_SDK_SECRET;
const geminiKey = process.env.GEMINI_API_KEY;
async function generateGeminiEphemeralToken() {
const client = new GoogleGenAI({ apiKey: geminiKey });
// Increase expiration times
const expireTime = new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(); // 2 hours
const newSessionExpireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString(); // 30 minutes
try {
const token = await client.authTokens.create({
config: {
uses: 1,
expireTime: expireTime,
newSessionExpireTime: newSessionExpireTime,
httpOptions: { apiVersion: 'v1alpha' },
},
});
console.log("Gemini Ephemeral Token Name:", token.name);
return token.name;
} catch (error) {
console.error("Error creating ephemeral token:", error);
throw error;
}
}
function validateEnvironment() {
if (!sdkKey || !sdkSecret) {
console.error(
chalk.red.bold("✗ Error:") +
" SDK_KEY and SDK_SECRET must be set in your environment or .env file",
);
console.error(
chalk.dim(" Please ensure your .env file contains both variables."),
);
process.exit(1);
}
if (sdkKey.trim() === "" || sdkSecret.trim() === "") {
console.error(
chalk.red.bold("✗ Error:") + " SDK_KEY and SDK_SECRET cannot be empty",
);
process.exit(1);
}
if (typeof window !== 'undefined') {
console.error("YOU ARE RUNNING THIS IN THE BROWSER. PLEASE RUN THIS IN THE TERMINAL.");
process.exit(1);
}
}
function generateSignature(
sessionName,
role,
expiresInHours = 2,
) {
const iat = Math.round(new Date().getTime() / 1000) - 30;
const exp = iat + 60 * 60 * expiresInHours;
const oHeader = { alg: "HS256", typ: "JWT" };
const oPayload = {
app_key: sdkKey,
tpc: sessionName,
role_type: role,
version: 1,
iat: iat,
exp: exp,
};
const sHeader = JSON.stringify(oHeader);
const sPayload = JSON.stringify(oPayload);
const sdkJWT = KJUR.KJUR.jws.JWS.sign("HS256", sHeader, sPayload, sdkSecret);
return sdkJWT;
}
function validateSessionName(sessionName) {
if (!sessionName || sessionName.trim() === "") {
console.error(chalk.red.bold("✗ Error:") + " Session name cannot be empty");
process.exit(1);
}
if (sessionName.length > 200) {
console.error(
chalk.red.bold("✗ Error:") +
" Session name is too long (max 200 characters)",
);
process.exit(1);
}
}
function validateRole(role) {
if (!Number.isInteger(role) || role < 0) {
console.error(
chalk.red.bold("✗ Error:") +
` Invalid role: ${role}. Role must be a non-negative integer.`,
);
process.exit(1);
}
if (role > 10) {
console.warn(
chalk.yellow.bold("⚠ Warning:") +
` Role ${role} is unusually high. Common values are 0 (host) or 1 (participant).`,
);
}
}
program
.name("generateToken")
.description(chalk.cyan("Generate a VideoSDK JWT token for a session"))
.version("1.0.0")
.argument("<sessionName>", "Name of the session/topic")
.option(
"-r, --role <number>",
"Role type (0 = host, 1 = participant, default: 1)",
"1",
)
.option(
"-e, --expires <hours>",
"Token expiration time in hours (default: 2)",
"2",
)
.option("-q, --quiet", "Output only the token, no color or extra info")
.option("-c, --copy-to-clipboard", "Copy the token to clipboard")
.showHelpAfterError()
.action(async (sessionName, options) => {
try {
validateEnvironment();
validateSessionName(sessionName);
const role = parseInt(options.role, 10);
if (isNaN(role)) {
console.error(
chalk.red.bold("✗ Error:") +
` Invalid role value: "${options.role}". Must be a number.`,
);
process.exit(1);
}
validateRole(role);
const expiresInHours = parseFloat(options.expires);
if (isNaN(expiresInHours) || expiresInHours <= 0) {
console.error(
chalk.red.bold("✗ Error:") +
` Invalid expiration time: "${options.expires}". Must be a positive number.`,
);
process.exit(1);
}
const token = generateSignature(sessionName, role, expiresInHours);
const geminiToken = await generateGeminiEphemeralToken();
if (options.quiet) {
console.log(token);
} else {
console.log(chalk.dim("Session:") + ` ${chalk.white(sessionName)}`);
console.log(chalk.dim("Role:") + ` ${chalk.white(role)}`);
console.log(
chalk.dim("Expires in:") +
` ${chalk.white(`${expiresInHours} hour(s)`)}`,
);
console.log(chalk.dim("\nToken:\n") + chalk.cyan(token));
console.log(chalk.dim("\nGemini Token:\n") + chalk.cyan(geminiToken));
}
if (options.copyToClipboard) {
try {
clipboardy.writeSync(token);
} catch (err) {
console.error("Failed to copy token to clipboard:", err);
process.exit(1);
}
}
} catch (error) {
console.error(
chalk.red.bold("✗ Error generating token:") +
` ${error instanceof Error ? error.message : String(error)}`,
);
process.exit(1);
}
});
program.parse();