b23-lib 1.1.0 → 1.1.1

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.
package/dist/index.d.mts CHANGED
@@ -238,27 +238,28 @@ declare const Schema: {
238
238
  declare class AuthUtility {
239
239
  private secretToken;
240
240
  private maxTokenAge;
241
- constructor({ secret, maxTokenAge }: {
242
- secret: string;
243
- maxTokenAge: string;
241
+ private anonymousPrivateKey;
242
+ private anonymousPublicKey;
243
+ constructor({ secret, maxTokenAge, anonymousPrivateKey, anonymousPublicKey }: {
244
+ secret?: string;
245
+ maxTokenAge?: string;
246
+ anonymousPrivateKey?: string;
247
+ anonymousPublicKey?: string;
244
248
  });
245
- createToken(id: string, additionalData: object): Promise<string>;
249
+ createAnonymousToken(id: string, additionalData?: object): Promise<string>;
250
+ verifyAnonymousToken(token: string): Promise<jose.JWTPayload>;
251
+ createToken(id: string, additionalData?: object): Promise<string>;
246
252
  verifyToken(token: string): Promise<jose.JWTPayload>;
247
- AuthMiddleware(): (req: any, res: any, next: any) => Promise<void>;
253
+ AuthMiddleware(allowAnonymous: boolean): (req: any, res: any, next: any) => Promise<void>;
248
254
  }
249
255
 
250
- declare const ResponseUtility: {
251
- handleException: (functionName: string, error: any, res: any) => void;
252
- generateResponse: (status: number, data?: any, error?: string) => {
253
- status: number;
254
- data: any;
255
- error: string | undefined;
256
- };
257
- generateError: (status: number, error: string, knownError?: Boolean, logError?: boolean) => {
258
- status: number;
259
- error: string;
260
- knownError: Boolean;
261
- logError: boolean;
256
+ declare const _default: {
257
+ isUUID: (value: string) => boolean;
258
+ generateUUID: (value?: string, namespace?: string) => string;
259
+ generateSearchId: (key: string, variantId: string) => string;
260
+ getKeyfromSearchId: (searchId: string) => {
261
+ key: string;
262
+ variantId: string;
262
263
  };
263
264
  };
264
265
 
@@ -276,4 +277,4 @@ declare const Logger: {
276
277
  logInvalidPayload: (functionName: string, errorMessage: string) => void;
277
278
  };
278
279
 
279
- export { AuthUtility as Auth, DynamoDBUtility as DynamoDB, Fetch, Logger, ResponseUtility, Schema };
280
+ export { AuthUtility as Auth, DynamoDBUtility as DynamoDB, Fetch, Logger, _default as ResponseUtility, Schema, _default as Utils };
package/dist/index.d.ts CHANGED
@@ -238,27 +238,28 @@ declare const Schema: {
238
238
  declare class AuthUtility {
239
239
  private secretToken;
240
240
  private maxTokenAge;
241
- constructor({ secret, maxTokenAge }: {
242
- secret: string;
243
- maxTokenAge: string;
241
+ private anonymousPrivateKey;
242
+ private anonymousPublicKey;
243
+ constructor({ secret, maxTokenAge, anonymousPrivateKey, anonymousPublicKey }: {
244
+ secret?: string;
245
+ maxTokenAge?: string;
246
+ anonymousPrivateKey?: string;
247
+ anonymousPublicKey?: string;
244
248
  });
245
- createToken(id: string, additionalData: object): Promise<string>;
249
+ createAnonymousToken(id: string, additionalData?: object): Promise<string>;
250
+ verifyAnonymousToken(token: string): Promise<jose.JWTPayload>;
251
+ createToken(id: string, additionalData?: object): Promise<string>;
246
252
  verifyToken(token: string): Promise<jose.JWTPayload>;
247
- AuthMiddleware(): (req: any, res: any, next: any) => Promise<void>;
253
+ AuthMiddleware(allowAnonymous: boolean): (req: any, res: any, next: any) => Promise<void>;
248
254
  }
249
255
 
250
- declare const ResponseUtility: {
251
- handleException: (functionName: string, error: any, res: any) => void;
252
- generateResponse: (status: number, data?: any, error?: string) => {
253
- status: number;
254
- data: any;
255
- error: string | undefined;
256
- };
257
- generateError: (status: number, error: string, knownError?: Boolean, logError?: boolean) => {
258
- status: number;
259
- error: string;
260
- knownError: Boolean;
261
- logError: boolean;
256
+ declare const _default: {
257
+ isUUID: (value: string) => boolean;
258
+ generateUUID: (value?: string, namespace?: string) => string;
259
+ generateSearchId: (key: string, variantId: string) => string;
260
+ getKeyfromSearchId: (searchId: string) => {
261
+ key: string;
262
+ variantId: string;
262
263
  };
263
264
  };
264
265
 
@@ -276,4 +277,4 @@ declare const Logger: {
276
277
  logInvalidPayload: (functionName: string, errorMessage: string) => void;
277
278
  };
278
279
 
279
- export { AuthUtility as Auth, DynamoDBUtility as DynamoDB, Fetch, Logger, ResponseUtility, Schema };
280
+ export { AuthUtility as Auth, DynamoDBUtility as DynamoDB, Fetch, Logger, _default as ResponseUtility, Schema, _default as Utils };
package/dist/index.js CHANGED
@@ -34,8 +34,9 @@ __export(src_exports, {
34
34
  DynamoDB: () => Dynamodb_default,
35
35
  Fetch: () => fetch_default,
36
36
  Logger: () => Logger_default,
37
- ResponseUtility: () => response_default,
38
- Schema: () => Schema_default
37
+ ResponseUtility: () => Utils_default,
38
+ Schema: () => Schema_default,
39
+ Utils: () => Utils_default
39
40
  });
40
41
  module.exports = __toCommonJS(src_exports);
41
42
 
@@ -414,8 +415,11 @@ var import_util2 = __toESM(require("util"));
414
415
 
415
416
  // src/enums/ErrorTypes.ts
416
417
  var ErrorTypes_default = Object.freeze({
418
+ INVALID_UUID: "Invalid UUID",
417
419
  INVALID_TOKEN: "Invalid Token",
418
420
  TOKEN_EXPIRED: "Token Expired",
421
+ INVALID_AUTH_TYPE: "Invalid Authorization Type",
422
+ ANONYMOUS_SESSION_NOT_ALLOWED: "Anonymous Session Not Allowed",
419
423
  INTERNAL_SERVER_ERROR: "Internal Server Error"
420
424
  });
421
425
 
@@ -437,6 +441,31 @@ var Logger = {
437
441
  };
438
442
  var Logger_default = Logger;
439
443
 
444
+ // src/Utils/index.ts
445
+ var import_uuid = require("uuid");
446
+ var Utils_default = {
447
+ isUUID: (value) => {
448
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
449
+ return uuidRegex.test(value);
450
+ },
451
+ generateUUID: (value, namespace) => {
452
+ if (namespace && value) {
453
+ return (0, import_uuid.v5)(value, namespace);
454
+ }
455
+ return (0, import_uuid.v4)();
456
+ },
457
+ generateSearchId: (key, variantId) => {
458
+ return `${key}#${variantId}`;
459
+ },
460
+ getKeyfromSearchId: (searchId) => {
461
+ const [key, variantId] = searchId.split("#");
462
+ return {
463
+ key,
464
+ variantId
465
+ };
466
+ }
467
+ };
468
+
440
469
  // src/Utils/response.ts
441
470
  var ResponseUtility = {
442
471
  handleException: (functionName, error, res) => {
@@ -473,14 +502,35 @@ var ResponseUtility = {
473
502
  var response_default = ResponseUtility;
474
503
 
475
504
  // src/Auth/index.ts
505
+ var import_assert = __toESM(require("assert"));
476
506
  var AuthUtility = class {
477
507
  secretToken;
478
508
  maxTokenAge;
479
- constructor({ secret, maxTokenAge = "30 days" }) {
509
+ anonymousPrivateKey;
510
+ anonymousPublicKey;
511
+ constructor({ secret = "", maxTokenAge = "30 days", anonymousPrivateKey = "", anonymousPublicKey = "" }) {
480
512
  this.secretToken = secret;
481
513
  this.maxTokenAge = maxTokenAge;
514
+ this.anonymousPrivateKey = anonymousPrivateKey;
515
+ this.anonymousPublicKey = anonymousPublicKey;
516
+ }
517
+ async createAnonymousToken(id, additionalData) {
518
+ (0, import_assert.default)(Utils_default.isUUID(id), ErrorTypes_default.INVALID_UUID);
519
+ const payload = {
520
+ id,
521
+ ...additionalData
522
+ };
523
+ const privateKey = await (0, import_jose.importPKCS8)(this.anonymousPrivateKey, "RS256");
524
+ const token = await new import_jose.SignJWT(payload).setProtectedHeader({ alg: "RS256" }).setExpirationTime(this.maxTokenAge).setIssuedAt().sign(privateKey);
525
+ return token;
526
+ }
527
+ async verifyAnonymousToken(token) {
528
+ const publicKey = await (0, import_jose.importSPKI)(this.anonymousPublicKey, "RS256");
529
+ const jwt = await (0, import_jose.jwtVerify)(token, publicKey, { clockTolerance: 30, maxTokenAge: this.maxTokenAge });
530
+ return jwt.payload;
482
531
  }
483
532
  async createToken(id, additionalData) {
533
+ (0, import_assert.default)(Utils_default.isUUID(id), ErrorTypes_default.INVALID_UUID);
484
534
  const payload = {
485
535
  id,
486
536
  ...additionalData
@@ -491,18 +541,37 @@ var AuthUtility = class {
491
541
  }
492
542
  async verifyToken(token) {
493
543
  const secretKey = Buffer.from(this.secretToken, "hex");
494
- const jwt = await (0, import_jose.jwtDecrypt)(token, secretKey, { maxTokenAge: this.maxTokenAge });
544
+ const jwt = await (0, import_jose.jwtDecrypt)(token, secretKey, { clockTolerance: 30, maxTokenAge: this.maxTokenAge });
495
545
  return jwt.payload;
496
546
  }
497
- AuthMiddleware() {
547
+ AuthMiddleware(allowAnonymous) {
498
548
  return async (req, res, next) => {
499
549
  try {
500
- const token = req.get("Authorization")?.split(" ")?.[1];
550
+ const [authType, token] = req.get("Authorization")?.split(" ");
501
551
  if (!token) {
502
552
  throw new Error(ErrorTypes_default.INVALID_TOKEN);
503
553
  }
504
- const payload = await this.verifyToken(token);
505
- res.locals.auth = payload;
554
+ let payload;
555
+ switch (authType) {
556
+ case "Anon":
557
+ if (!allowAnonymous) {
558
+ throw response_default.generateError(403, ErrorTypes_default.ANONYMOUS_SESSION_NOT_ALLOWED, true, true);
559
+ }
560
+ payload = await this.verifyAnonymousToken(token);
561
+ break;
562
+ case "User":
563
+ payload = await this.verifyToken(token);
564
+ break;
565
+ case "System":
566
+ break;
567
+ default:
568
+ throw response_default.generateError(403, ErrorTypes_default.INVALID_AUTH_TYPE, true, true);
569
+ }
570
+ res.locals.auth = {
571
+ authType,
572
+ token,
573
+ ...payload
574
+ };
506
575
  next();
507
576
  } catch (error) {
508
577
  Logger_default.logError("AuthMiddleware", import_util2.default.inspect(error));
@@ -565,5 +634,6 @@ var fetch_default = Fetch;
565
634
  Fetch,
566
635
  Logger,
567
636
  ResponseUtility,
568
- Schema
637
+ Schema,
638
+ Utils
569
639
  });
package/dist/index.mjs CHANGED
@@ -383,13 +383,16 @@ var Schema = {
383
383
  var Schema_default = Schema;
384
384
 
385
385
  // src/Auth/index.ts
386
- import { EncryptJWT, jwtDecrypt } from "jose";
386
+ import { EncryptJWT, importPKCS8, importSPKI, jwtDecrypt, jwtVerify, SignJWT } from "jose";
387
387
  import util2 from "util";
388
388
 
389
389
  // src/enums/ErrorTypes.ts
390
390
  var ErrorTypes_default = Object.freeze({
391
+ INVALID_UUID: "Invalid UUID",
391
392
  INVALID_TOKEN: "Invalid Token",
392
393
  TOKEN_EXPIRED: "Token Expired",
394
+ INVALID_AUTH_TYPE: "Invalid Authorization Type",
395
+ ANONYMOUS_SESSION_NOT_ALLOWED: "Anonymous Session Not Allowed",
393
396
  INTERNAL_SERVER_ERROR: "Internal Server Error"
394
397
  });
395
398
 
@@ -411,6 +414,31 @@ var Logger = {
411
414
  };
412
415
  var Logger_default = Logger;
413
416
 
417
+ // src/Utils/index.ts
418
+ import { v4 as uuidv4, v5 as uuidv5 } from "uuid";
419
+ var Utils_default = {
420
+ isUUID: (value) => {
421
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
422
+ return uuidRegex.test(value);
423
+ },
424
+ generateUUID: (value, namespace) => {
425
+ if (namespace && value) {
426
+ return uuidv5(value, namespace);
427
+ }
428
+ return uuidv4();
429
+ },
430
+ generateSearchId: (key, variantId) => {
431
+ return `${key}#${variantId}`;
432
+ },
433
+ getKeyfromSearchId: (searchId) => {
434
+ const [key, variantId] = searchId.split("#");
435
+ return {
436
+ key,
437
+ variantId
438
+ };
439
+ }
440
+ };
441
+
414
442
  // src/Utils/response.ts
415
443
  var ResponseUtility = {
416
444
  handleException: (functionName, error, res) => {
@@ -447,14 +475,35 @@ var ResponseUtility = {
447
475
  var response_default = ResponseUtility;
448
476
 
449
477
  // src/Auth/index.ts
478
+ import assert from "assert";
450
479
  var AuthUtility = class {
451
480
  secretToken;
452
481
  maxTokenAge;
453
- constructor({ secret, maxTokenAge = "30 days" }) {
482
+ anonymousPrivateKey;
483
+ anonymousPublicKey;
484
+ constructor({ secret = "", maxTokenAge = "30 days", anonymousPrivateKey = "", anonymousPublicKey = "" }) {
454
485
  this.secretToken = secret;
455
486
  this.maxTokenAge = maxTokenAge;
487
+ this.anonymousPrivateKey = anonymousPrivateKey;
488
+ this.anonymousPublicKey = anonymousPublicKey;
489
+ }
490
+ async createAnonymousToken(id, additionalData) {
491
+ assert(Utils_default.isUUID(id), ErrorTypes_default.INVALID_UUID);
492
+ const payload = {
493
+ id,
494
+ ...additionalData
495
+ };
496
+ const privateKey = await importPKCS8(this.anonymousPrivateKey, "RS256");
497
+ const token = await new SignJWT(payload).setProtectedHeader({ alg: "RS256" }).setExpirationTime(this.maxTokenAge).setIssuedAt().sign(privateKey);
498
+ return token;
499
+ }
500
+ async verifyAnonymousToken(token) {
501
+ const publicKey = await importSPKI(this.anonymousPublicKey, "RS256");
502
+ const jwt = await jwtVerify(token, publicKey, { clockTolerance: 30, maxTokenAge: this.maxTokenAge });
503
+ return jwt.payload;
456
504
  }
457
505
  async createToken(id, additionalData) {
506
+ assert(Utils_default.isUUID(id), ErrorTypes_default.INVALID_UUID);
458
507
  const payload = {
459
508
  id,
460
509
  ...additionalData
@@ -465,18 +514,37 @@ var AuthUtility = class {
465
514
  }
466
515
  async verifyToken(token) {
467
516
  const secretKey = Buffer.from(this.secretToken, "hex");
468
- const jwt = await jwtDecrypt(token, secretKey, { maxTokenAge: this.maxTokenAge });
517
+ const jwt = await jwtDecrypt(token, secretKey, { clockTolerance: 30, maxTokenAge: this.maxTokenAge });
469
518
  return jwt.payload;
470
519
  }
471
- AuthMiddleware() {
520
+ AuthMiddleware(allowAnonymous) {
472
521
  return async (req, res, next) => {
473
522
  try {
474
- const token = req.get("Authorization")?.split(" ")?.[1];
523
+ const [authType, token] = req.get("Authorization")?.split(" ");
475
524
  if (!token) {
476
525
  throw new Error(ErrorTypes_default.INVALID_TOKEN);
477
526
  }
478
- const payload = await this.verifyToken(token);
479
- res.locals.auth = payload;
527
+ let payload;
528
+ switch (authType) {
529
+ case "Anon":
530
+ if (!allowAnonymous) {
531
+ throw response_default.generateError(403, ErrorTypes_default.ANONYMOUS_SESSION_NOT_ALLOWED, true, true);
532
+ }
533
+ payload = await this.verifyAnonymousToken(token);
534
+ break;
535
+ case "User":
536
+ payload = await this.verifyToken(token);
537
+ break;
538
+ case "System":
539
+ break;
540
+ default:
541
+ throw response_default.generateError(403, ErrorTypes_default.INVALID_AUTH_TYPE, true, true);
542
+ }
543
+ res.locals.auth = {
544
+ authType,
545
+ token,
546
+ ...payload
547
+ };
480
548
  next();
481
549
  } catch (error) {
482
550
  Logger_default.logError("AuthMiddleware", util2.inspect(error));
@@ -537,6 +605,7 @@ export {
537
605
  Dynamodb_default as DynamoDB,
538
606
  fetch_default as Fetch,
539
607
  Logger_default as Logger,
540
- response_default as ResponseUtility,
541
- Schema_default as Schema
608
+ Utils_default as ResponseUtility,
609
+ Schema_default as Schema,
610
+ Utils_default as Utils
542
611
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "b23-lib",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "This repo hold common classes, type and util functiona",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -19,7 +19,7 @@
19
19
  "dependencies": {
20
20
  "@aws-sdk/client-dynamodb": "^3.620.0",
21
21
  "@aws-sdk/util-dynamodb": "^3.620.0",
22
- "jose": "^5.9.6",
22
+ "jose": "^5.6.3",
23
23
  "util": "^0.12.5"
24
24
  },
25
25
  "devDependencies": {