-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.js
349 lines (317 loc) · 13.8 KB
/
core.js
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// eslint-disable-next-line no-redeclare
const SwaggerUIAuthorizerModule = (() => {
return {
assetsCache: {},
apiCache: null,
authorizations: [],
delay: function (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
},
waitForSwaggerFunctions: async function () {
let attempts = 100;
while (attempts) {
try {
this.getAPI();
return;
} catch {
await this.delay(500);
attempts--;
}
}
throw new Error('Swagger UI is not ready');
},
getDateDifferenceInMinutes: function (date1, date2) {
const diff = Math.abs(date1 - date2);
return Math.floor((diff / 1000) / 60);
},
getAPI: function () {
if (this.apiCache) return this.apiCache;
this.apiCache = this.mapToObject(window.ui.spec()).json;
return this.apiCache;
},
getRequestSchemas: function (schema) {
const API = this.getAPI();
return schema ? API.components.schemas[schema] : API.components.schemas;
},
getRequestInfoByOperationId: function (operationId) {
const API = this.getAPI();
const paths = API.paths;
for (const path in paths) {
for (const method in paths[path]) {
const operation = paths[path][method];
if (operation.operationId === operationId) {
return {
path,
method,
operation
};
}
}
}
return null;
},
resolveRef: function (schema) {
const definitions = this.getAPI().components.schemas;
if (schema.$ref) {
const refPath = schema.$ref.split('/').pop();
return definitions[refPath];
}
return schema;
},
createJsonObjectFromSchema: function (schema) {
const definitions = this.getAPI().components.schemas;
schema = this.resolveRef(schema, definitions);
if (!schema || typeof schema !== 'object') {
return null;
}
if (schema.type === 'object') {
const obj = {};
for (const key in schema.properties) {
obj[key] = this.createJsonObjectFromSchema(schema.properties[key], definitions);
}
return obj;
}
if (schema.type === 'array') {
return [this.createJsonObjectFromSchema(schema.items, definitions)];
}
// Handle primitive types
switch (schema.type) {
case 'string':
return '';
case 'number':
return 0;
case 'integer':
return 0;
case 'boolean':
return false;
default:
return null;
}
},
getSecuritySchemes: function (name) {
const API = this.getAPI();
const securitySchemesObj = API.components.securitySchemes;
const securitySchemes = Object.keys(securitySchemesObj).map(scheme => ({ ...securitySchemesObj[scheme], security_scheme_name: scheme }));
return name ? securitySchemes.find((scheme) => scheme.security_scheme_name === name) : securitySchemes;
},
getSavedSecurity: function (name) {
const system = window.ui.getSystem();
const authorized = system.authSelectors.authorized();
const authorizedObject = this.mapToObject(authorized);
return name ? authorizedObject[name] : authorizedObject;
},
getSecurityRequirementsByOperationId: function (operationId) {
const requestInfo = this.getRequestInfoByOperationId(operationId);
if (requestInfo && requestInfo.operation.security) {
return requestInfo.operation.security.map(security => Object.keys(security)).flat();
}
return null;
},
getRequestQueryParams: function (operationId) {
const request = this.getRequestInfoByOperationId(operationId);
const queryParams = request.operation.parameters.filter((param) => param.in === 'query');
if (!queryParams.length) return {};
return queryParams.reduce((acc, param) => {
acc[param.name] = '';
return acc;
}, {});
},
getRequestPathParams: function (operationId) {
const request = this.getRequestInfoByOperationId(operationId);
const pathParams = request.operation.parameters.filter((param) => param.in === 'path');
if (!pathParams.length) return {};
return pathParams.reduce((acc, param) => {
acc[param.name] = '';
return acc;
}, {});
},
getRequestHeadersParams: function (operationId) {
const request = this.getRequestInfoByOperationId(operationId);
const headersParams = request.operation.parameters.filter((param) => param.in === 'header');
if (!headersParams.length) return {};
return headersParams.reduce((acc, param) => {
acc[param.name] = '';
return acc;
}, {});
},
getRequestBodyParams: function (operationId) {
const request = SwaggerUIAuthorizerModule.getRequestInfoByOperationId(operationId);
if (!request.operation.requestBody) return {};
try {
if (request.operation.requestBody.content['application/json']) {
const schema = request.operation.requestBody.content['application/json'].schema;
const schemaObject = this.createJsonObjectFromSchema(schema);
return schemaObject;
}
} catch (error) {
return {};
}
},
mapToObject: function (map) {
return JSON.parse(JSON.stringify(map));
},
base64UrlDecode: function (str) {
str = str
.replace(/-/g, '+')
.replace(/_/g, '/');
while (str.length % 4) {
str += '=';
}
return atob(str);
},
isJWT: function (token) {
const parts = token.split('.');
return parts.length === 3;
},
validateJWT: function (token) {
if (!this.isJWT(token)) {
return false;
}
try {
const payload = JSON.parse(this.base64UrlDecode(token.split('.')[1]));
return payload && payload.exp && payload.exp > Date.now() / 1000;
} catch (error) {
return false;
}
},
getValueByPath: function (root, path) {
return path.split('.').reduce((acc, segment) => acc && acc[segment], root);
},
waitForSelector: function (selector, callback) {
const seen = new WeakSet();
const observer = new MutationObserver(() => {
document.querySelectorAll(selector).forEach((element) => {
if (!seen.has(element)) {
seen.add(element);
callback(element);
}
});
});
observer.observe(document.body, { childList: true, subtree: true });
},
preAuthorize: async function (params) {
try {
const API = this.getAPI();
const operationId = params[0].operationId;
const securityRequirements = this.getSecurityRequirementsByOperationId(operationId);
if (!securityRequirements) return params;
for (const securityRequirement of securityRequirements) {
const securityScheme = this.getSecuritySchemes(securityRequirement);
// Check if the operation requires authentication
if (['bearer', 'basic', 'apiKey'].includes(securityScheme.scheme) || securityScheme.type === 'apiKey') {
// Get the profile
const authorizations = this.getSavedAuthorizations();
const authorization = authorizations.find(profile => profile.security_scheme_name === securityRequirement && profile.current);
if (authorization) {
if (!authorizations.length) return params;
if (authorization.profile_type === 'credentials') {
window.ui.preauthorizeBasic(securityRequirement, authorization.parameters.login, authorization.parameters.password);
const authorizedMap = window.ui.getSystem().authSelectors.authorized();
const authorized = this.mapToObject(authorizedMap);
params[0].securities.authorized = authorized;
}
if (authorization.profile_type === 'value') {
window.ui.preauthorizeApiKey(securityRequirement, authorization.parameters.auth_value);
const authorizedMap = window.ui.getSystem().authSelectors.authorized();
const authorized = this.mapToObject(authorizedMap);
params[0].securities.authorized = authorized;
}
if (authorization.profile_type === 'request') {
// Check if request is already authorized
const currentAuthorization = params[0].securities.authorized && params[0].securities.authorized[securityRequirement];
if (currentAuthorization && this.isJWT(currentAuthorization.value) && this.validateJWT(currentAuthorization.value)) return params;
if (authorization.parameters.auth_value_ttl && authorization.parameters.auth_value_date) {
const ttl = authorization.parameters.auth_value_ttl;
const authValueDate = new Date(authorization.parameters.auth_value_date);
const isTokenExpired = this.getDateDifferenceInMinutes(new Date(), authValueDate) > ttl;
if (!isTokenExpired) return params;
}
const authRequestInfo = this.getRequestInfoByOperationId(authorization.parameters.operation_id);
// Get the parameters
const authRequestParams = authorization.parameters;
const prebuildRequest = window.ui.getSystem().fn.buildRequest({
spec: API,
operationId: authRequestInfo.operation.operationId,
parameters: { ...authRequestParams.parameters, ...authRequestParams.query },
securities: { authorized: this.mapToObject(window.ui.getSystem().authSelectors.authorized()) },
bodyParams: authRequestParams.body,
});
// Execute the request
const response = await window.ui.getSystem().fn.fetch({
...prebuildRequest,
headers: {
'Content-Type': 'application/json',
...prebuildRequest.headers,
...authRequestParams.headers
},
parameters: authRequestParams.parameters,
...(authRequestInfo.method === 'get' ? {} : { body: JSON.stringify(authRequestParams.body || {}) }),
});
const token = this.getValueByPath(response, authorization.parameters.auth_value_source.replace(/^response\./, ''));
if (!token) {
alert(`SwaggerUIAuthorizer preauth error \n\nToken not found in response object \n\n Please check path: ${authorization.parameters.auth_value_source} in response object`);
return params;
}
window.ui.preauthorizeApiKey(securityRequirement, token);
const authorizedMap = window.ui.getSystem().authSelectors.authorized();
const authorized = this.mapToObject(authorizedMap);
const localStorageAuthorized = localStorage.getItem('authorized');
if (!localStorageAuthorized) {
localStorage.setItem('authorized', JSON.stringify(authorized));
} else {
const localStorageAuthorizedMap = JSON.parse(localStorageAuthorized);
localStorage.setItem('authorized', JSON.stringify({ ...localStorageAuthorizedMap, ...authorized }));
}
authorization.parameters.auth_value_date = new Date().toISOString();
this.saveAuthorization(authorization);
params[0].securities.authorized = authorized;
}
}
}
}
} catch (error) {
alert(`SwaggerUIAuthorizer preauth error \n\n${error.message}`);
}
return params;
},
unauthorize: function (scheme) {
const system = window.ui.getSystem();
const authorized = this.getSavedSecurity();
delete authorized[scheme];
system.authActions.logout([scheme]);
const authorizedMap = system.authSelectors.authorized();
const authorizedObject = this.mapToObject(authorizedMap);
localStorage.setItem('authorized', JSON.stringify(authorizedObject));
},
getSavedAuthorizations: function () {
const authorizations = JSON.parse(window.localStorage.getItem('swagger-ui-authorizations')) || [];
this.authorizations = authorizations;
return authorizations;
},
saveAuthorization: function (authorization) {
if (authorization.id) {
const index = this.authorizations.findIndex((auth) => auth.id === authorization.id);
if (index > -1) this.authorizations[index] = authorization;
} else {
this.authorizations.push({ id: new Date().getTime().toString(), ...authorization });
}
window.localStorage.setItem('swagger-ui-authorizations', JSON.stringify(this.authorizations));
},
removeAuthorization: function (id) {
this.authorizations = this.authorizations.filter((auth) => auth.id !== id);
window.localStorage.setItem('swagger-ui-authorizations', JSON.stringify(this.authorizations));
},
getTextAsset: async function (path) {
if (this.assetsCache[path]) {
while (this.assetsCache[path].status === 'loading') await this.delay(5);
return this.assetsCache[path].value;
}
this.assetsCache[path] = { value: null, status: 'loading' };
const url = chrome.runtime.getURL(path);
const raw = await fetch(url);
const response = await raw.text();
this.assetsCache[path] = { value: response, status: 'loaded' };
return response;
},
}
})();