-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathjwt.ts
More file actions
211 lines (186 loc) · 5.97 KB
/
jwt.ts
File metadata and controls
211 lines (186 loc) · 5.97 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import * as vscode from 'vscode';
import { Commands } from '../constants';
import { executeCommand } from '../utils/shell';
import { getDevProxyExe } from '../detect';
import { VersionPreference } from '../enums';
import * as logger from '../logger';
/**
* JWT (JSON Web Token) generation commands.
*/
export function registerJwtCommands(
context: vscode.ExtensionContext,
configuration: vscode.WorkspaceConfiguration
): void {
const versionPreference = configuration.get('version') as VersionPreference;
const devProxyExe = getDevProxyExe(versionPreference);
context.subscriptions.push(
vscode.commands.registerCommand(Commands.jwtCreate, () => createJwt(devProxyExe))
);
}
/**
* JWT creation parameters collected from user input.
*/
interface JwtParams {
name: string;
issuer: string;
audiences: string[];
roles: string[];
scopes: string[];
claims: string[];
validFor: number;
}
async function createJwt(devProxyExe: string): Promise<void> {
const params = await collectJwtParams();
if (!params) {
logger.debug('JWT creation cancelled by user');
return; // User cancelled
}
logger.info('Generating JWT', { name: params.name, issuer: params.issuer, audiences: params.audiences.length, roles: params.roles.length, scopes: params.scopes.length, validFor: params.validFor });
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: 'Generating JWT...',
cancellable: false,
},
async () => {
try {
const command = buildJwtCommand(devProxyExe, params);
const result = await executeCommand(command);
const token = extractToken(result);
logger.info('JWT token generated successfully');
await presentToken(token, command);
} catch (error) {
logger.error('Failed to generate JWT token', error);
vscode.window.showErrorMessage(`Failed to generate JWT token: ${error}`);
}
}
);
}
async function collectJwtParams(): Promise<JwtParams | undefined> {
const name = await promptForInput({
prompt: 'Enter the name of the user to create the token for',
placeHolder: 'Dev Proxy',
value: 'Dev Proxy',
title: 'JWT Generation - User Name',
});
if (name === undefined) {
return undefined;
}
const issuer = await promptForInput({
prompt: 'Enter the issuer of the token',
placeHolder: 'dev-proxy',
value: 'dev-proxy',
title: 'JWT Generation - Issuer',
});
if (issuer === undefined) {
return undefined;
}
const audiencesStr = await promptForInput({
prompt: 'Enter the audiences (comma-separated for multiple)',
placeHolder: 'https://myserver.com',
value: 'https://myserver.com',
title: 'JWT Generation - Audiences',
});
if (audiencesStr === undefined) {
return undefined;
}
const rolesStr = await promptForInput({
prompt: 'Enter roles (comma-separated, leave empty for none)',
placeHolder: 'admin,user',
value: '',
title: 'JWT Generation - Roles (Optional)',
});
if (rolesStr === undefined) {
return undefined;
}
const scopesStr = await promptForInput({
prompt: 'Enter scopes (comma-separated, leave empty for none)',
placeHolder: 'read,write',
value: '',
title: 'JWT Generation - Scopes (Optional)',
});
if (scopesStr === undefined) {
return undefined;
}
const claimsStr = await promptForInput({
prompt: 'Enter custom claims in format name:value (comma-separated, leave empty for none)',
placeHolder: 'custom:claim,department:engineering',
value: '',
title: 'JWT Generation - Custom Claims (Optional)',
});
if (claimsStr === undefined) {
return undefined;
}
const validForStr = await promptForInput({
prompt: 'Enter token validity duration in minutes',
placeHolder: '60',
value: '60',
title: 'JWT Generation - Validity Duration',
validateInput: (value: string) => {
const num = parseInt(value);
if (isNaN(num) || num <= 0) {
return 'Please enter a positive number';
}
return undefined;
},
});
if (validForStr === undefined) {
return undefined;
}
return {
name,
issuer,
audiences: parseList(audiencesStr),
roles: parseList(rolesStr),
scopes: parseList(scopesStr),
claims: parseList(claimsStr).filter(c => c.includes(':')),
validFor: parseInt(validForStr),
};
}
function promptForInput(options: vscode.InputBoxOptions): Thenable<string | undefined> {
return vscode.window.showInputBox(options);
}
function parseList(value: string): string[] {
return value
.split(',')
.map(s => s.trim())
.filter(s => s.length > 0);
}
function buildJwtCommand(devProxyExe: string, params: JwtParams): string {
let command = `${devProxyExe} jwt create --name "${params.name}" --issuer "${params.issuer}" --valid-for ${params.validFor}`;
params.audiences.forEach(audience => {
command += ` --audiences "${audience}"`;
});
params.roles.forEach(role => {
command += ` --roles "${role}"`;
});
params.scopes.forEach(scope => {
command += ` --scopes "${scope}"`;
});
params.claims.forEach(claim => {
command += ` --claims "${claim}"`;
});
return command;
}
function extractToken(result: string): string {
const lines = result.split('\n').filter(line => line.trim());
return lines[lines.length - 1].trim();
}
async function presentToken(token: string, command: string): Promise<void> {
const choice = await vscode.window.showInformationMessage(
'JWT generated successfully!',
{ modal: true },
'Copy to Clipboard',
'Show Token'
);
if (choice === 'Copy to Clipboard') {
await vscode.env.clipboard.writeText(token);
vscode.window.showInformationMessage('JWT copied to clipboard');
} else if (choice === 'Show Token') {
const document = await vscode.workspace.openTextDocument({
content: `JWT Generated: ${new Date().toISOString()}\n\nToken: ${token}\n\nCommand used:\n${command}`,
language: 'plaintext',
});
await vscode.window.showTextDocument(document);
}
}