@verdaccio/auth 8.0.0-next-8.11 → 8.0.0-next-8.13

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.
Files changed (39) hide show
  1. package/README.md +30 -24
  2. package/package.json +16 -12
  3. package/.babelrc +0 -3
  4. package/CHANGELOG.md +0 -1755
  5. package/src/auth.ts +0 -607
  6. package/src/index.ts +0 -3
  7. package/src/signature-legacy.ts +0 -66
  8. package/src/types.ts +0 -46
  9. package/src/utils.ts +0 -252
  10. package/test/auth-utils-middleware.spec.ts +0 -260
  11. package/test/auth-utils.spec.ts +0 -362
  12. package/test/auth.spec.ts +0 -722
  13. package/test/helper/plugin.ts +0 -43
  14. package/test/partials/config/yaml/security/security-basic.yaml +0 -12
  15. package/test/partials/config/yaml/security/security-empty.yaml +0 -1
  16. package/test/partials/config/yaml/security/security-jwt-legacy-enabled.yaml +0 -10
  17. package/test/partials/config/yaml/security/security-jwt.yaml +0 -6
  18. package/test/partials/config/yaml/security/security-legacy-disabled.yaml +0 -3
  19. package/test/partials/config/yaml/security/security-legacy.yaml +0 -3
  20. package/test/partials/config/yaml/security/security-missing.yaml +0 -0
  21. package/test/partials/config/yaml/security/security-no-legacy.yaml +0 -9
  22. package/test/partials/plugin/verdaccio-access-ok/access.js +0 -9
  23. package/test/partials/plugin/verdaccio-access-ok/package.json +0 -5
  24. package/test/partials/plugin/verdaccio-adduser/adduser.js +0 -25
  25. package/test/partials/plugin/verdaccio-adduser/package.json +0 -5
  26. package/test/partials/plugin/verdaccio-adduser-legacy/adduser.js +0 -25
  27. package/test/partials/plugin/verdaccio-adduser-legacy/package.json +0 -5
  28. package/test/partials/plugin/verdaccio-change-password/change.js +0 -32
  29. package/test/partials/plugin/verdaccio-change-password/package.json +0 -5
  30. package/test/partials/plugin/verdaccio-fail/fail.js +0 -14
  31. package/test/partials/plugin/verdaccio-fail/package.json +0 -5
  32. package/test/partials/plugin/verdaccio-fail-invalid-method/fail.js +0 -11
  33. package/test/partials/plugin/verdaccio-fail-invalid-method/package.json +0 -5
  34. package/test/partials/plugin/verdaccio-passthroug/package.json +0 -5
  35. package/test/partials/plugin/verdaccio-passthroug/passthroug.js +0 -9
  36. package/test/partials/plugin/verdaccio-success/package.json +0 -5
  37. package/test/partials/plugin/verdaccio-success/success.js +0 -9
  38. package/tsconfig.build.json +0 -9
  39. package/tsconfig.json +0 -32
package/src/auth.ts DELETED
@@ -1,607 +0,0 @@
1
- import buildDebug from 'debug';
2
- import _ from 'lodash';
3
- import { HTPasswd } from 'verdaccio-htpasswd';
4
-
5
- import { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';
6
- import {
7
- API_ERROR,
8
- PLUGIN_CATEGORY,
9
- SUPPORT_ERRORS,
10
- TOKEN_BASIC,
11
- TOKEN_BEARER,
12
- VerdaccioError,
13
- errorUtils,
14
- pluginUtils,
15
- warningUtils,
16
- } from '@verdaccio/core';
17
- import { asyncLoadPlugin } from '@verdaccio/loaders';
18
- import {
19
- aesEncrypt,
20
- aesEncryptDeprecated,
21
- parseBasicPayload,
22
- signPayload,
23
- utils as signatureUtils,
24
- } from '@verdaccio/signature';
25
- import {
26
- AllowAccess,
27
- Callback,
28
- Config,
29
- JWTSignOptions,
30
- Logger,
31
- PackageAccess,
32
- RemoteUser,
33
- Security,
34
- } from '@verdaccio/types';
35
- import { getMatchedPackagesSpec, isFunction, isNil } from '@verdaccio/utils';
36
-
37
- import {
38
- $RequestExtend,
39
- $ResponseExtend,
40
- AESPayload,
41
- IAuthMiddleware,
42
- NextFunction,
43
- TokenEncryption,
44
- } from './types';
45
- import {
46
- convertPayloadToBase64,
47
- getDefaultPlugins,
48
- getMiddlewareCredentials,
49
- isAESLegacy,
50
- isAuthHeaderValid,
51
- parseAuthTokenHeader,
52
- verifyJWTPayload,
53
- } from './utils';
54
-
55
- const debug = buildDebug('verdaccio:auth');
56
-
57
- class Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {
58
- public config: Config;
59
- public secret: string;
60
- public logger: Logger;
61
- public plugins: pluginUtils.Auth<Config>[];
62
-
63
- public constructor(config: Config, logger: Logger) {
64
- this.config = config;
65
- this.secret = config.secret;
66
- this.logger = logger;
67
- this.plugins = [];
68
- if (!this.secret) {
69
- throw new TypeError('secret it is required value on initialize the auth class');
70
- }
71
- }
72
-
73
- public async init() {
74
- let plugins = (await this.loadPlugin()) as pluginUtils.Auth<unknown>[];
75
-
76
- debug('auth plugins found %s', plugins.length);
77
- if (!plugins || plugins.length === 0) {
78
- plugins = this.loadDefaultPlugin();
79
- }
80
- this.plugins = plugins;
81
-
82
- this._applyDefaultPlugins();
83
- }
84
-
85
- private loadDefaultPlugin() {
86
- debug('load default auth plugin');
87
- const pluginOptions: pluginUtils.PluginOptions = {
88
- config: this.config,
89
- logger: this.logger,
90
- };
91
- let authPlugin;
92
- try {
93
- authPlugin = new HTPasswd(
94
- { file: './htpasswd' },
95
- pluginOptions as any as pluginUtils.PluginOptions
96
- );
97
- this.logger.info(
98
- { name: 'verdaccio-htpasswd', pluginCategory: PLUGIN_CATEGORY.AUTHENTICATION },
99
- 'plugin @{name} successfully loaded (@{pluginCategory})'
100
- );
101
- } catch (error: any) {
102
- debug('error on loading auth htpasswd plugin stack: %o', error);
103
- this.logger.info({}, 'no auth plugin has been found');
104
- return [];
105
- }
106
-
107
- return [authPlugin];
108
- }
109
-
110
- private async loadPlugin() {
111
- return asyncLoadPlugin<pluginUtils.Auth<unknown>>(
112
- this.config.auth,
113
- {
114
- config: this.config,
115
- logger: this.logger,
116
- },
117
- (plugin): boolean => {
118
- const { authenticate, allow_access, allow_publish } = plugin;
119
-
120
- return (
121
- typeof authenticate !== 'undefined' ||
122
- typeof allow_access !== 'undefined' ||
123
- typeof allow_publish !== 'undefined'
124
- );
125
- },
126
- this.config?.serverSettings?.pluginPrefix,
127
- PLUGIN_CATEGORY.AUTHENTICATION
128
- );
129
- }
130
-
131
- private _applyDefaultPlugins(): void {
132
- // TODO: rename to applyFallbackPluginMethods
133
- this.plugins.push(getDefaultPlugins(this.logger));
134
- }
135
-
136
- public changePassword(
137
- username: string,
138
- password: string,
139
- newPassword: string,
140
- cb: Callback
141
- ): void {
142
- const validPlugins = _.filter(this.plugins, (plugin) => isFunction(plugin.changePassword));
143
-
144
- if (_.isEmpty(validPlugins)) {
145
- return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));
146
- }
147
-
148
- for (const plugin of validPlugins) {
149
- if (isNil(plugin) || isFunction(plugin.changePassword) === false) {
150
- debug('auth plugin does not implement changePassword, trying next one');
151
- continue;
152
- } else {
153
- debug('updating password for %o', username);
154
- plugin.changePassword!(username, password, newPassword, (err, profile): void => {
155
- if (err) {
156
- this.logger.error(
157
- { username, err },
158
- `An error has been produced
159
- updating the password for @{username}. Error: @{err.message}`
160
- );
161
- return cb(err);
162
- }
163
-
164
- debug('updated password for %o was successful', username);
165
- return cb(null, profile);
166
- });
167
- }
168
- }
169
- }
170
-
171
- public async invalidateToken(token: string) {
172
- // eslint-disable-next-line no-console
173
- console.log('invalidate token pending to implement', token);
174
- return Promise.resolve();
175
- }
176
-
177
- public authenticate(
178
- username: string,
179
- password: string,
180
- cb: (error: VerdaccioError | null, user?: RemoteUser) => void
181
- ): void {
182
- const plugins = this.plugins.slice(0);
183
- (function next(): void {
184
- const plugin = plugins.shift() as pluginUtils.Auth<Config>;
185
-
186
- if (isFunction(plugin.authenticate) === false) {
187
- return next();
188
- }
189
-
190
- debug('authenticating %o', username);
191
- plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {
192
- if (err) {
193
- debug('authenticating for user %o failed. Error: %o', username, err?.message);
194
- return cb(err);
195
- }
196
-
197
- // Expect: SKIP if groups is falsey and not an array
198
- // with at least one item (truthy length)
199
- // Expect: CONTINUE otherwise (will error if groups is not
200
- // an array, but this is current behavior)
201
- // Caveat: STRING (if valid) will pass successfully
202
- // bug give unexpected results
203
- // Info: Cannot use `== false to check falsey values`
204
- if (!!groups && groups.length !== 0) {
205
- // TODO: create a better understanding of expectations
206
- if (_.isString(groups)) {
207
- throw new TypeError('plugin group error: invalid type for function');
208
- }
209
- const isGroupValid: boolean = _.isArray(groups);
210
- if (!isGroupValid) {
211
- throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);
212
- }
213
-
214
- debug('authentication for user %o was successfully. Groups: %o', username, groups);
215
- return cb(err, createRemoteUser(username, groups));
216
- }
217
- next();
218
- });
219
- })();
220
- }
221
-
222
- public add_user(
223
- user: string,
224
- password: string,
225
- cb: (error: VerdaccioError | null, user?: RemoteUser) => void
226
- ): void {
227
- const self = this;
228
- const plugins = this.plugins.slice(0);
229
- debug('add user %o', user);
230
-
231
- (function next(): void {
232
- let method = 'adduser';
233
- const plugin = plugins.shift() as pluginUtils.Auth<Config>;
234
- // @ts-expect-error future major (7.x) should remove this section
235
- if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {
236
- method = 'add_user';
237
- warningUtils.emit(warningUtils.Codes.VERWAR006);
238
- }
239
- // @ts-ignore
240
- if (typeof plugin[method] !== 'function') {
241
- next();
242
- } else {
243
- // TODO: replace by adduser whenever add_user deprecation method has been removed
244
- // @ts-ignore
245
- plugin[method](
246
- user,
247
- password,
248
- function (err: VerdaccioError | null, ok?: boolean | string): void {
249
- if (err) {
250
- debug('the user %o could not be added. Error: %o', user, err?.message);
251
- return cb(err);
252
- }
253
- if (ok) {
254
- debug('the user %o has been added', user);
255
- return self.authenticate(user, password, cb);
256
- }
257
- debug('user could not be added, skip to next auth plugin');
258
- next();
259
- }
260
- );
261
- }
262
- })();
263
- }
264
-
265
- /**
266
- * Allow user to access a package.
267
- */
268
- public allow_access(
269
- { packageName, packageVersion }: pluginUtils.AuthPluginPackage,
270
- user: RemoteUser,
271
- callback: pluginUtils.AccessCallback
272
- ): void {
273
- const plugins = this.plugins.slice(0);
274
- const pkgAllowAccess: AllowAccess = { name: packageName, version: packageVersion };
275
- const pkg = Object.assign(
276
- {},
277
- pkgAllowAccess,
278
- getMatchedPackagesSpec(packageName, this.config.packages)
279
- ) as AllowAccess & PackageAccess;
280
- debug('allow access for %o', packageName);
281
-
282
- (function next(): void {
283
- const plugin: pluginUtils.Auth<unknown> = plugins.shift() as pluginUtils.Auth<unknown>;
284
-
285
- if (_.isNil(plugin) || isFunction(plugin.allow_access) === false) {
286
- return next();
287
- }
288
-
289
- plugin.allow_access!(user, pkg, function (err: VerdaccioError | null, ok?: boolean): void {
290
- if (err) {
291
- debug('forbidden access for %o. Error: %o', packageName, err?.message);
292
- return callback(err);
293
- }
294
-
295
- if (ok) {
296
- debug('allowed access for %o', packageName);
297
- return callback(null, ok);
298
- }
299
-
300
- next(); // cb(null, false) causes next plugin to roll
301
- });
302
- })();
303
- }
304
-
305
- public allow_unpublish(
306
- { packageName, packageVersion }: pluginUtils.AuthPluginPackage,
307
- user: RemoteUser,
308
- callback: Callback
309
- ): void {
310
- const pkg = Object.assign(
311
- { name: packageName, version: packageVersion },
312
- getMatchedPackagesSpec(packageName, this.config.packages)
313
- );
314
- debug('allow unpublish for %o', packageName);
315
-
316
- for (const plugin of this.plugins) {
317
- if (typeof plugin?.allow_unpublish !== 'function') {
318
- debug('allow unpublish for %o plugin does not implement allow_unpublish', packageName);
319
- continue;
320
- } else {
321
- plugin.allow_unpublish(user, pkg, (err, ok): void => {
322
- if (err) {
323
- debug(
324
- 'forbidden publish for %o, it will fallback on unpublish permissions',
325
- packageName
326
- );
327
- return callback(err);
328
- }
329
-
330
- if (_.isNil(ok) === true) {
331
- debug('bypass unpublish for %o, publish will handle the access', packageName);
332
- return this.allow_publish({ packageName, packageVersion }, user, callback);
333
- }
334
-
335
- if (ok) {
336
- debug('allowed unpublish for %o', packageName);
337
- return callback(null, ok);
338
- }
339
- });
340
- }
341
- }
342
- }
343
-
344
- /**
345
- * Allow user to publish a package.
346
- */
347
- public allow_publish(
348
- { packageName, packageVersion }: pluginUtils.AuthPluginPackage,
349
- user: RemoteUser,
350
- callback: Callback
351
- ): void {
352
- const plugins = this.plugins.slice(0);
353
- const pkg = Object.assign(
354
- { name: packageName, version: packageVersion },
355
- getMatchedPackagesSpec(packageName, this.config.packages)
356
- );
357
- debug('allow publish for %o init | plugins: %o', packageName, plugins.length);
358
-
359
- (function next(): void {
360
- const plugin = plugins.shift();
361
-
362
- if (typeof plugin?.allow_publish !== 'function') {
363
- debug('allow publish for %o plugin does not implement allow_publish', packageName);
364
- return next();
365
- }
366
-
367
- plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {
368
- if (_.isNil(err) === false && _.isError(err)) {
369
- debug('forbidden publish for %o', packageName);
370
- return callback(err);
371
- }
372
-
373
- if (ok) {
374
- debug('allowed publish for %o', packageName);
375
- return callback(null, ok);
376
- }
377
-
378
- debug('allow publish skip validation for %o', packageName);
379
- next(); // cb(null, false) causes next plugin to roll
380
- });
381
- })();
382
- }
383
-
384
- public apiJWTmiddleware(): any {
385
- debug('jwt middleware');
386
- const plugins = this.plugins.slice(0);
387
- const helpers = { createAnonymousRemoteUser, createRemoteUser };
388
- for (const plugin of plugins) {
389
- if (plugin.apiJWTmiddleware) {
390
- return plugin.apiJWTmiddleware(helpers);
391
- }
392
- }
393
-
394
- return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {
395
- req.pause();
396
- const next = function (err?: VerdaccioError): NextFunction {
397
- req.resume();
398
- // uncomment this to reject users with bad auth headers
399
- // return _next.apply(null, arguments)
400
- // swallow error, user remains unauthorized
401
- // set remoteUserError to indicate that user was attempting authentication
402
- if (err) {
403
- req.remote_user.error = err.message;
404
- }
405
-
406
- return _next() as unknown as NextFunction;
407
- };
408
-
409
- // FUTURE: disabled, not removed yet but seems unreacable code
410
- // if (this._isRemoteUserValid(req.remote_user)) {
411
- // debug('jwt has a valid authentication header');
412
- // return next();
413
- // }
414
-
415
- // in case auth header does not exist we return anonymous function
416
- const remoteUser = createAnonymousRemoteUser();
417
- req.remote_user = remoteUser;
418
- res.locals.remote_user = remoteUser;
419
-
420
- const { authorization } = req.headers;
421
- if (_.isNil(authorization)) {
422
- debug('jwt, authentication header is missing');
423
- return next();
424
- }
425
-
426
- if (!isAuthHeaderValid(authorization)) {
427
- debug('api middleware authentication heather is invalid');
428
- return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));
429
- }
430
- const { secret, security } = this.config;
431
-
432
- if (isAESLegacy(security)) {
433
- debug('api middleware using legacy auth token');
434
- this.handleAESMiddleware(req, security, secret, authorization, next);
435
- } else {
436
- debug('api middleware using JWT auth token');
437
- this.handleJWTAPIMiddleware(req, security, secret, authorization, next);
438
- }
439
- };
440
- }
441
-
442
- private handleJWTAPIMiddleware(
443
- req: $RequestExtend,
444
- security: Security,
445
- secret: string,
446
- authorization: string,
447
- next: any
448
- ): void {
449
- debug('handle JWT api middleware');
450
- const { scheme, token } = parseAuthTokenHeader(authorization);
451
- if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {
452
- debug('handle basic token');
453
- // this should happen when client tries to login with an existing user
454
- const credentials = convertPayloadToBase64(token).toString();
455
- const { user, password } = parseBasicPayload(credentials) as AESPayload;
456
- debug('authenticating %o', user);
457
- this.authenticate(user, password, (err: VerdaccioError | null, user): void => {
458
- if (!err) {
459
- debug('generating a remote user');
460
- req.remote_user = user;
461
- next();
462
- } else {
463
- debug('generating anonymous user');
464
- req.remote_user = createAnonymousRemoteUser();
465
- next(err);
466
- }
467
- });
468
- } else {
469
- debug('handle jwt token');
470
- const credentials: any = getMiddlewareCredentials(security, secret, authorization);
471
- if (credentials) {
472
- // if the signature is valid we rely on it
473
- req.remote_user = credentials;
474
- debug('generating a remote user');
475
- next();
476
- } else {
477
- // with JWT throw 401
478
- debug('jwt invalid token');
479
- next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));
480
- }
481
- }
482
- }
483
-
484
- private handleAESMiddleware(
485
- req: $RequestExtend,
486
- security: Security,
487
- secret: string,
488
- authorization: string,
489
- next: Function
490
- ): void {
491
- debug('handle legacy api middleware');
492
- debug('api middleware has a secret? %o', typeof secret === 'string');
493
- debug('api middleware authorization %o', typeof authorization === 'string');
494
- const credentials: any = getMiddlewareCredentials(security, secret, authorization);
495
- debug('api middleware credentials %o', credentials?.name);
496
- if (credentials) {
497
- const { user, password } = credentials;
498
- debug('authenticating %o', user);
499
- this.authenticate(user, password, (err, user): void => {
500
- if (!err) {
501
- req.remote_user = user;
502
- debug('generating a remote user');
503
- next();
504
- } else {
505
- req.remote_user = createAnonymousRemoteUser();
506
- debug('generating anonymous user');
507
- next(err);
508
- }
509
- });
510
- } else {
511
- // we force npm client to ask again with basic authentication
512
- debug('legacy invalid header');
513
- return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));
514
- }
515
- }
516
-
517
- private _isRemoteUserValid(remote_user?: RemoteUser): boolean {
518
- return _.isUndefined(remote_user) === false && _.isUndefined(remote_user?.name) === false;
519
- }
520
-
521
- /**
522
- * JWT middleware for WebUI
523
- */
524
- public webUIJWTmiddleware() {
525
- return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {
526
- if (this._isRemoteUserValid(req.remote_user)) {
527
- return _next();
528
- }
529
-
530
- req.pause();
531
- const next = (err: VerdaccioError | void): void => {
532
- req.resume();
533
- if (err) {
534
- req.remote_user.error = err.message;
535
- res.status(err.statusCode).send(err.message);
536
- }
537
-
538
- return _next();
539
- };
540
-
541
- const { authorization } = req.headers;
542
- if (_.isNil(authorization)) {
543
- return next();
544
- }
545
-
546
- if (!isAuthHeaderValid(authorization)) {
547
- return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));
548
- }
549
-
550
- const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');
551
- if (!token) {
552
- return next();
553
- }
554
-
555
- let credentials: RemoteUser | undefined;
556
- try {
557
- credentials = verifyJWTPayload(token, this.config.secret);
558
- } catch (err: any) {
559
- // FIXME: intended behaviour, do we want it?
560
- }
561
-
562
- if (this._isRemoteUserValid(credentials)) {
563
- const { name, groups } = credentials as RemoteUser;
564
- req.remote_user = createRemoteUser(name as string, groups);
565
- } else {
566
- req.remote_user = createAnonymousRemoteUser();
567
- }
568
-
569
- next();
570
- };
571
- }
572
-
573
- public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {
574
- const { real_groups, name, groups } = user;
575
- debug('jwt encrypt %o', name);
576
- const realGroupsValidated = _.isNil(real_groups) ? [] : real_groups;
577
- const groupedGroups = _.isNil(groups)
578
- ? real_groups
579
- : Array.from(new Set([...groups.concat(realGroupsValidated)]));
580
- const payload: RemoteUser = {
581
- real_groups: realGroupsValidated,
582
- name,
583
- groups: groupedGroups,
584
- };
585
- const token: string = await signPayload(payload, this.secret, signOptions);
586
-
587
- return token;
588
- }
589
-
590
- /**
591
- * Encrypt a string.
592
- */
593
- public aesEncrypt(value: string): string | void {
594
- if (this.secret.length === signatureUtils.TOKEN_VALID_LENGTH) {
595
- debug('signing with enhanced aes legacy');
596
- const token = aesEncrypt(value, this.secret);
597
- return token;
598
- } else {
599
- debug('signing with enhanced aes deprecated legacy');
600
- // deprecated aes (legacy) signature, only must be used for legacy version
601
- const token = aesEncryptDeprecated(Buffer.from(value), this.secret).toString('base64');
602
- return token;
603
- }
604
- }
605
- }
606
-
607
- export { Auth };
package/src/index.ts DELETED
@@ -1,3 +0,0 @@
1
- export { Auth } from './auth';
2
- export * from './utils';
3
- export * from './types';
@@ -1,66 +0,0 @@
1
- import buildDebug from 'debug';
2
- import _ from 'lodash';
3
-
4
- import { TOKEN_BASIC, TOKEN_BEARER } from '@verdaccio/core';
5
- import { aesDecryptDeprecated as aesDecrypt, parseBasicPayload } from '@verdaccio/signature';
6
- import { Security } from '@verdaccio/types';
7
-
8
- import { AuthMiddlewarePayload } from './types';
9
- import {
10
- convertPayloadToBase64,
11
- isAESLegacy,
12
- parseAuthTokenHeader,
13
- verifyJWTPayload,
14
- } from './utils';
15
-
16
- const debug = buildDebug('verdaccio:auth:utils');
17
-
18
- export function parseAESCredentials(authorizationHeader: string, secret: string) {
19
- debug('parseAESCredentials');
20
- const { scheme, token } = parseAuthTokenHeader(authorizationHeader);
21
-
22
- // basic is deprecated and should not be enforced
23
- // basic is currently being used for functional test
24
- if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {
25
- debug('legacy header basic');
26
- const credentials = convertPayloadToBase64(token).toString();
27
-
28
- return credentials;
29
- } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {
30
- debug('legacy header bearer');
31
- const credentials = aesDecrypt(Buffer.from(token), secret);
32
-
33
- return credentials;
34
- }
35
- }
36
-
37
- export function getMiddlewareCredentials(
38
- security: Security,
39
- secretKey: string,
40
- authorizationHeader: string
41
- ): AuthMiddlewarePayload {
42
- debug('getMiddlewareCredentials');
43
- // comment out for debugging purposes
44
- if (isAESLegacy(security)) {
45
- debug('is legacy');
46
- const credentials = parseAESCredentials(authorizationHeader, secretKey);
47
- if (typeof credentials !== 'string') {
48
- debug('parse legacy credentials failed');
49
- return;
50
- }
51
-
52
- const parsedCredentials = parseBasicPayload(credentials);
53
- if (!parsedCredentials) {
54
- debug('parse legacy basic payload credentials failed');
55
- return;
56
- }
57
-
58
- return parsedCredentials;
59
- }
60
- const { scheme, token } = parseAuthTokenHeader(authorizationHeader);
61
-
62
- debug('is jwt');
63
- if (_.isString(token) && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {
64
- return verifyJWTPayload(token, secretKey);
65
- }
66
- }