b23-lib 1.7.0 → 1.7.2

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 (127) hide show
  1. package/dist/Auth/index.d.mts +130 -0
  2. package/dist/Auth/index.d.ts +130 -0
  3. package/dist/Auth/index.js +2 -0
  4. package/dist/Auth/index.js.map +1 -0
  5. package/dist/Auth/index.mjs +2 -0
  6. package/dist/Auth/index.mjs.map +1 -0
  7. package/dist/Classes/Address.d.mts +142 -0
  8. package/dist/Classes/Address.d.ts +142 -0
  9. package/dist/Classes/Address.js +2 -0
  10. package/dist/Classes/Address.js.map +1 -0
  11. package/dist/Classes/Address.mjs +2 -0
  12. package/dist/Classes/Address.mjs.map +1 -0
  13. package/dist/Classes/Base.d.mts +98 -0
  14. package/dist/Classes/Base.d.ts +98 -0
  15. package/dist/Classes/Base.js +2 -0
  16. package/dist/Classes/Base.js.map +1 -0
  17. package/dist/Classes/Base.mjs +2 -0
  18. package/dist/Classes/Base.mjs.map +1 -0
  19. package/dist/Classes/Cart.d.mts +68 -0
  20. package/dist/Classes/Cart.d.ts +68 -0
  21. package/dist/Classes/Cart.js +2 -0
  22. package/dist/Classes/Cart.js.map +1 -0
  23. package/dist/Classes/Cart.mjs +2 -0
  24. package/dist/Classes/Cart.mjs.map +1 -0
  25. package/dist/Classes/Common.d.mts +75 -0
  26. package/dist/Classes/Common.d.ts +75 -0
  27. package/dist/Classes/Common.js +2 -0
  28. package/dist/Classes/Common.js.map +1 -0
  29. package/dist/Classes/Common.mjs +2 -0
  30. package/dist/Classes/Common.mjs.map +1 -0
  31. package/dist/Classes/Coupon.d.mts +142 -0
  32. package/dist/Classes/Coupon.d.ts +142 -0
  33. package/dist/Classes/Coupon.js +2 -0
  34. package/dist/Classes/Coupon.js.map +1 -0
  35. package/dist/Classes/Coupon.mjs +2 -0
  36. package/dist/Classes/Coupon.mjs.map +1 -0
  37. package/dist/Classes/Customer.d.mts +97 -0
  38. package/dist/Classes/Customer.d.ts +97 -0
  39. package/dist/Classes/Customer.js +2 -0
  40. package/dist/Classes/Customer.js.map +1 -0
  41. package/dist/Classes/Customer.mjs +2 -0
  42. package/dist/Classes/Customer.mjs.map +1 -0
  43. package/dist/Classes/CustomerAddress.d.mts +71 -0
  44. package/dist/Classes/CustomerAddress.d.ts +71 -0
  45. package/dist/Classes/CustomerAddress.js +2 -0
  46. package/dist/Classes/CustomerAddress.js.map +1 -0
  47. package/dist/Classes/CustomerAddress.mjs +2 -0
  48. package/dist/Classes/CustomerAddress.mjs.map +1 -0
  49. package/dist/Classes/Enum.d.mts +34 -0
  50. package/dist/Classes/Enum.d.ts +34 -0
  51. package/dist/Classes/Enum.js +2 -0
  52. package/dist/Classes/Enum.js.map +1 -0
  53. package/dist/Classes/Enum.mjs +2 -0
  54. package/dist/Classes/Enum.mjs.map +1 -0
  55. package/dist/Classes/ImageInfo.d.mts +92 -0
  56. package/dist/Classes/ImageInfo.d.ts +92 -0
  57. package/dist/Classes/ImageInfo.js +2 -0
  58. package/dist/Classes/ImageInfo.js.map +1 -0
  59. package/dist/Classes/ImageInfo.mjs +2 -0
  60. package/dist/Classes/ImageInfo.mjs.map +1 -0
  61. package/dist/Classes/LineItem.d.mts +124 -0
  62. package/dist/Classes/LineItem.d.ts +124 -0
  63. package/dist/Classes/LineItem.js +2 -0
  64. package/dist/Classes/LineItem.js.map +1 -0
  65. package/dist/Classes/LineItem.mjs +2 -0
  66. package/dist/Classes/LineItem.mjs.map +1 -0
  67. package/dist/Classes/Order.d.mts +83 -0
  68. package/dist/Classes/Order.d.ts +83 -0
  69. package/dist/Classes/Order.js +2 -0
  70. package/dist/Classes/Order.js.map +1 -0
  71. package/dist/Classes/Order.mjs +2 -0
  72. package/dist/Classes/Order.mjs.map +1 -0
  73. package/dist/Classes/Payment.d.mts +161 -0
  74. package/dist/Classes/Payment.d.ts +161 -0
  75. package/dist/Classes/Payment.js +2 -0
  76. package/dist/Classes/Payment.js.map +1 -0
  77. package/dist/Classes/Payment.mjs +2 -0
  78. package/dist/Classes/Payment.mjs.map +1 -0
  79. package/dist/Classes/Price.d.mts +70 -0
  80. package/dist/Classes/Price.d.ts +70 -0
  81. package/dist/Classes/Price.js +2 -0
  82. package/dist/Classes/Price.js.map +1 -0
  83. package/dist/Classes/Price.mjs +2 -0
  84. package/dist/Classes/Price.mjs.map +1 -0
  85. package/dist/Classes/Product.d.mts +209 -0
  86. package/dist/Classes/Product.d.ts +209 -0
  87. package/dist/Classes/Product.js +2 -0
  88. package/dist/Classes/Product.js.map +1 -0
  89. package/dist/Classes/Product.mjs +2 -0
  90. package/dist/Classes/Product.mjs.map +1 -0
  91. package/dist/Classes/ShoppingContainer.d.mts +194 -0
  92. package/dist/Classes/ShoppingContainer.d.ts +194 -0
  93. package/dist/Classes/ShoppingContainer.js +2 -0
  94. package/dist/Classes/ShoppingContainer.js.map +1 -0
  95. package/dist/Classes/ShoppingContainer.mjs +2 -0
  96. package/dist/Classes/ShoppingContainer.mjs.map +1 -0
  97. package/dist/Dynamodb/index.d.mts +58 -0
  98. package/dist/Dynamodb/index.d.ts +58 -0
  99. package/dist/Dynamodb/index.js +2 -0
  100. package/dist/Dynamodb/index.js.map +1 -0
  101. package/dist/Dynamodb/index.mjs +2 -0
  102. package/dist/Dynamodb/index.mjs.map +1 -0
  103. package/dist/chunk-4H4LJ3UL.mjs +2 -0
  104. package/dist/chunk-4H4LJ3UL.mjs.map +1 -0
  105. package/dist/chunk-65X54TKF.mjs +2 -0
  106. package/dist/chunk-65X54TKF.mjs.map +1 -0
  107. package/dist/chunk-763MN5XV.mjs +2 -0
  108. package/dist/chunk-763MN5XV.mjs.map +1 -0
  109. package/dist/chunk-CWKGR4AF.mjs +2 -0
  110. package/dist/chunk-CWKGR4AF.mjs.map +1 -0
  111. package/dist/chunk-DKI6BDWK.mjs +2 -0
  112. package/dist/chunk-DKI6BDWK.mjs.map +1 -0
  113. package/dist/chunk-SPLTJRHG.mjs +2 -0
  114. package/dist/chunk-SPLTJRHG.mjs.map +1 -0
  115. package/dist/chunk-T6IVHYQQ.mjs +2 -0
  116. package/dist/chunk-T6IVHYQQ.mjs.map +1 -0
  117. package/dist/chunk-T6YCHB3K.mjs +2 -0
  118. package/dist/chunk-T6YCHB3K.mjs.map +1 -0
  119. package/dist/chunk-WU6FFDBS.mjs +2 -0
  120. package/dist/chunk-WU6FFDBS.mjs.map +1 -0
  121. package/dist/index.d.mts +1 -624
  122. package/dist/index.d.ts +1 -624
  123. package/dist/index.js +2 -1
  124. package/dist/index.js.map +1 -1
  125. package/dist/index.mjs +2 -1
  126. package/dist/index.mjs.map +1 -1
  127. package/package.json +163 -1
@@ -0,0 +1,130 @@
1
+ import * as jose from 'jose';
2
+
3
+ type StringifiedJSONArray = string;
4
+ interface AuthUtilityConfig {
5
+ maxTokenAge: string;
6
+ userPrivateKeys: StringifiedJSONArray;
7
+ userPublicKeys: StringifiedJSONArray;
8
+ anonymousPrivateKeys: StringifiedJSONArray;
9
+ anonymousPublicKeys: StringifiedJSONArray;
10
+ systemPrivateKeys: StringifiedJSONArray;
11
+ systemPublicKeys: StringifiedJSONArray;
12
+ adminPrivateKeys: StringifiedJSONArray;
13
+ adminPublicKeys: StringifiedJSONArray;
14
+ }
15
+ declare const DefaultAuthUtilityConfig: Readonly<AuthUtilityConfig>;
16
+ type AuthTokenType = 'Anon' | 'User' | 'System' | 'Admin' | 'CDN';
17
+ interface AuthMiddlewareConfig {
18
+ allowAnonymous: boolean;
19
+ allowSystem: boolean;
20
+ allowUser: boolean;
21
+ allowCDN: boolean;
22
+ }
23
+ declare const DefaultAuthMiddlewareConfig: Readonly<AuthMiddlewareConfig>;
24
+ /**
25
+ * A utility class for JWT authentication and authorization.
26
+ */
27
+ declare class AuthUtility {
28
+ private maxTokenAge;
29
+ private userPrivateKeys;
30
+ private userPublicKeys;
31
+ private anonymousPrivateKeys;
32
+ private anonymousPublicKeys;
33
+ private systemPrivateKeys;
34
+ private systemPublicKeys;
35
+ private adminPrivateKeys;
36
+ private adminPublicKeys;
37
+ /**
38
+ * Initializes the AuthUtility class with a configuration.
39
+ * @param config The configuration for the utility (optional).
40
+ */
41
+ constructor(config?: Partial<AuthUtilityConfig>);
42
+ /**
43
+ * Logs warnings if the number of keys exceeds recommended limits.
44
+ */
45
+ private logWarnings;
46
+ private createSignedJWT;
47
+ private verifySignedJWT;
48
+ /**
49
+ * Creates an anonymous token with the given ID and additional data.
50
+ *
51
+ * @param id - The unique identifier for the token. Must be a valid UUID.
52
+ * @param additionalData - Optional additional data to include in the token payload.
53
+ * @returns A promise that resolves to the signed JWT as a string.
54
+ * @throws Will throw an error if no anonymous private keys are found or if the ID is not a valid UUID.
55
+ */
56
+ createAnonymousToken(id: string, additionalData?: object): Promise<string>;
57
+ /**
58
+ * Verifies an anonymous token by checking its signature and payload type.
59
+ *
60
+ * @param token - The JWT token to be verified.
61
+ * @returns The payload of the verified token.
62
+ * @throws Will throw an error if no anonymous public keys are found or if the token type is invalid.
63
+ */
64
+ verifyAnonymousToken(token: string): Promise<jose.JWTPayload>;
65
+ /**
66
+ * Creates a signed JWT token for a user.
67
+ *
68
+ * @param id - The UUID of the user.
69
+ * @param additionalData - Optional additional data to include in the token payload.
70
+ * @returns A promise that resolves to the signed JWT token as a string.
71
+ * @throws Will throw an error if no user private keys are found or if the provided id is not a valid UUID.
72
+ */
73
+ createUserToken(id: string, additionalData?: object): Promise<string>;
74
+ /**
75
+ * Verifies the provided user token by checking its signature and payload.
76
+ *
77
+ * @param token - The JWT token to be verified.
78
+ * @returns The payload of the verified token if valid.
79
+ * @throws Will throw an error if no user public keys are found or if the token type is invalid.
80
+ */
81
+ verifyUserToken(token: string): Promise<jose.JWTPayload>;
82
+ /**
83
+ * Creates a signed JWT (JSON Web Token) for a system with the given ID and optional additional data.
84
+ *
85
+ * @param id - The unique identifier for the system.
86
+ * @param additionalData - Optional additional data to include in the token payload.
87
+ * @returns A promise that resolves to the signed JWT as a string.
88
+ * @throws Will throw an error if no system private keys are found.
89
+ */
90
+ createSystemToken(id: string, additionalData?: object): Promise<string>;
91
+ /**
92
+ * Verifies a system token by checking its signature and payload type.
93
+ *
94
+ * @param token - The JWT token to be verified.
95
+ * @returns The payload of the verified token.
96
+ * @throws Will throw an error if no system public keys are found or if the token type is not 'System'.
97
+ */
98
+ verifySystemToken(token: string): Promise<jose.JWTPayload>;
99
+ /**
100
+ * Creates a signed JWT token for an admin user.
101
+ *
102
+ * @param email - The email of the admin user.
103
+ * @param additionalData - Optional additional data to include in the token payload.
104
+ * @returns A promise that resolves to the signed JWT token string.
105
+ * @throws Will throw an error if no admin private keys are found or if the provided id is not a valid UUID.
106
+ */
107
+ createAdminToken(email: string, verifier: string, additionalData?: object): Promise<string>;
108
+ /**
109
+ * Verifies the provided admin token by checking its signature and payload.
110
+ * Ensures that the token is signed with one of the known admin public keys
111
+ * and that the payload type is 'Admin'.
112
+ *
113
+ * @param token - The JWT token to be verified.
114
+ * @param permissions - The permissions required for the admin user.
115
+ * @param authenticate - Whether to authenticate the token with the verifier.
116
+ * @returns The payload of the verified token.
117
+ * @throws Will throw an error if no admin public keys are found or if the token is invalid or if the admin doesn't have proper permissions.
118
+ */
119
+ verifyAdminToken(token: string, permissions: string[], authenticate: boolean): Promise<jose.JWTPayload>;
120
+ /**
121
+ * Middleware function to handle authentication based on different token types.
122
+ * It verifies the token and sets the authentication details in the response locals.
123
+ *
124
+ * @param {Partial<AuthMiddlewareConfig>} [config=DefaultAuthMiddlewareConfig] - Configuration object to customize the middleware behavior.
125
+ * @returns Middleware function to handle authentication.
126
+ */
127
+ AuthMiddleware(config?: Partial<AuthMiddlewareConfig>, permissions?: string[]): (req: any, res: any, next: any) => Promise<void>;
128
+ }
129
+
130
+ export { type AuthMiddlewareConfig, type AuthTokenType, type AuthUtilityConfig, DefaultAuthMiddlewareConfig, DefaultAuthUtilityConfig, AuthUtility as default };
@@ -0,0 +1,130 @@
1
+ import * as jose from 'jose';
2
+
3
+ type StringifiedJSONArray = string;
4
+ interface AuthUtilityConfig {
5
+ maxTokenAge: string;
6
+ userPrivateKeys: StringifiedJSONArray;
7
+ userPublicKeys: StringifiedJSONArray;
8
+ anonymousPrivateKeys: StringifiedJSONArray;
9
+ anonymousPublicKeys: StringifiedJSONArray;
10
+ systemPrivateKeys: StringifiedJSONArray;
11
+ systemPublicKeys: StringifiedJSONArray;
12
+ adminPrivateKeys: StringifiedJSONArray;
13
+ adminPublicKeys: StringifiedJSONArray;
14
+ }
15
+ declare const DefaultAuthUtilityConfig: Readonly<AuthUtilityConfig>;
16
+ type AuthTokenType = 'Anon' | 'User' | 'System' | 'Admin' | 'CDN';
17
+ interface AuthMiddlewareConfig {
18
+ allowAnonymous: boolean;
19
+ allowSystem: boolean;
20
+ allowUser: boolean;
21
+ allowCDN: boolean;
22
+ }
23
+ declare const DefaultAuthMiddlewareConfig: Readonly<AuthMiddlewareConfig>;
24
+ /**
25
+ * A utility class for JWT authentication and authorization.
26
+ */
27
+ declare class AuthUtility {
28
+ private maxTokenAge;
29
+ private userPrivateKeys;
30
+ private userPublicKeys;
31
+ private anonymousPrivateKeys;
32
+ private anonymousPublicKeys;
33
+ private systemPrivateKeys;
34
+ private systemPublicKeys;
35
+ private adminPrivateKeys;
36
+ private adminPublicKeys;
37
+ /**
38
+ * Initializes the AuthUtility class with a configuration.
39
+ * @param config The configuration for the utility (optional).
40
+ */
41
+ constructor(config?: Partial<AuthUtilityConfig>);
42
+ /**
43
+ * Logs warnings if the number of keys exceeds recommended limits.
44
+ */
45
+ private logWarnings;
46
+ private createSignedJWT;
47
+ private verifySignedJWT;
48
+ /**
49
+ * Creates an anonymous token with the given ID and additional data.
50
+ *
51
+ * @param id - The unique identifier for the token. Must be a valid UUID.
52
+ * @param additionalData - Optional additional data to include in the token payload.
53
+ * @returns A promise that resolves to the signed JWT as a string.
54
+ * @throws Will throw an error if no anonymous private keys are found or if the ID is not a valid UUID.
55
+ */
56
+ createAnonymousToken(id: string, additionalData?: object): Promise<string>;
57
+ /**
58
+ * Verifies an anonymous token by checking its signature and payload type.
59
+ *
60
+ * @param token - The JWT token to be verified.
61
+ * @returns The payload of the verified token.
62
+ * @throws Will throw an error if no anonymous public keys are found or if the token type is invalid.
63
+ */
64
+ verifyAnonymousToken(token: string): Promise<jose.JWTPayload>;
65
+ /**
66
+ * Creates a signed JWT token for a user.
67
+ *
68
+ * @param id - The UUID of the user.
69
+ * @param additionalData - Optional additional data to include in the token payload.
70
+ * @returns A promise that resolves to the signed JWT token as a string.
71
+ * @throws Will throw an error if no user private keys are found or if the provided id is not a valid UUID.
72
+ */
73
+ createUserToken(id: string, additionalData?: object): Promise<string>;
74
+ /**
75
+ * Verifies the provided user token by checking its signature and payload.
76
+ *
77
+ * @param token - The JWT token to be verified.
78
+ * @returns The payload of the verified token if valid.
79
+ * @throws Will throw an error if no user public keys are found or if the token type is invalid.
80
+ */
81
+ verifyUserToken(token: string): Promise<jose.JWTPayload>;
82
+ /**
83
+ * Creates a signed JWT (JSON Web Token) for a system with the given ID and optional additional data.
84
+ *
85
+ * @param id - The unique identifier for the system.
86
+ * @param additionalData - Optional additional data to include in the token payload.
87
+ * @returns A promise that resolves to the signed JWT as a string.
88
+ * @throws Will throw an error if no system private keys are found.
89
+ */
90
+ createSystemToken(id: string, additionalData?: object): Promise<string>;
91
+ /**
92
+ * Verifies a system token by checking its signature and payload type.
93
+ *
94
+ * @param token - The JWT token to be verified.
95
+ * @returns The payload of the verified token.
96
+ * @throws Will throw an error if no system public keys are found or if the token type is not 'System'.
97
+ */
98
+ verifySystemToken(token: string): Promise<jose.JWTPayload>;
99
+ /**
100
+ * Creates a signed JWT token for an admin user.
101
+ *
102
+ * @param email - The email of the admin user.
103
+ * @param additionalData - Optional additional data to include in the token payload.
104
+ * @returns A promise that resolves to the signed JWT token string.
105
+ * @throws Will throw an error if no admin private keys are found or if the provided id is not a valid UUID.
106
+ */
107
+ createAdminToken(email: string, verifier: string, additionalData?: object): Promise<string>;
108
+ /**
109
+ * Verifies the provided admin token by checking its signature and payload.
110
+ * Ensures that the token is signed with one of the known admin public keys
111
+ * and that the payload type is 'Admin'.
112
+ *
113
+ * @param token - The JWT token to be verified.
114
+ * @param permissions - The permissions required for the admin user.
115
+ * @param authenticate - Whether to authenticate the token with the verifier.
116
+ * @returns The payload of the verified token.
117
+ * @throws Will throw an error if no admin public keys are found or if the token is invalid or if the admin doesn't have proper permissions.
118
+ */
119
+ verifyAdminToken(token: string, permissions: string[], authenticate: boolean): Promise<jose.JWTPayload>;
120
+ /**
121
+ * Middleware function to handle authentication based on different token types.
122
+ * It verifies the token and sets the authentication details in the response locals.
123
+ *
124
+ * @param {Partial<AuthMiddlewareConfig>} [config=DefaultAuthMiddlewareConfig] - Configuration object to customize the middleware behavior.
125
+ * @returns Middleware function to handle authentication.
126
+ */
127
+ AuthMiddleware(config?: Partial<AuthMiddlewareConfig>, permissions?: string[]): (req: any, res: any, next: any) => Promise<void>;
128
+ }
129
+
130
+ export { type AuthMiddlewareConfig, type AuthTokenType, type AuthUtilityConfig, DefaultAuthMiddlewareConfig, DefaultAuthUtilityConfig, AuthUtility as default };
@@ -0,0 +1,2 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var jose=require('jose'),V=require('util'),C=require('crypto'),y=require('assert');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var V__default=/*#__PURE__*/_interopDefault(V);var C__default=/*#__PURE__*/_interopDefault(C);var y__default=/*#__PURE__*/_interopDefault(y);var i=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong"});var E={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${E.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${E.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${E.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${E.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${E.inspect(e)}`);},inspect:t=>typeof t=="string"?t:V__default.default.inspect(t)},m=E;var A=new Uint8Array(256),h=A.length;function I(){return h>A.length-16&&(C__default.default.randomFillSync(A),h=0),A.slice(h,h+=16)}var x=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Y(t){return typeof t=="string"&&x.test(t)}var D=Y;var l=[];for(let t=0;t<256;++t)l.push((t+256).toString(16).slice(1));function _(t,e=0){return l[t[e+0]]+l[t[e+1]]+l[t[e+2]]+l[t[e+3]]+"-"+l[t[e+4]]+l[t[e+5]]+"-"+l[t[e+6]]+l[t[e+7]]+"-"+l[t[e+8]]+l[t[e+9]]+"-"+l[t[e+10]]+l[t[e+11]]+l[t[e+12]]+l[t[e+13]]+l[t[e+14]]+l[t[e+15]]}function J(t){if(!D(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var w=J;function W(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var $="6ba7b810-9dad-11d1-80b4-00c04fd430c8",j="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function P(t,e,r){function s(n,o,g,a){var p;if(typeof n=="string"&&(n=W(n)),typeof o=="string"&&(o=w(o)),((p=o)===null||p===void 0?void 0:p.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,g){a=a||0;for(let d=0;d<16;++d)g[a+d]=u[d];return g}return _(u)}try{s.name=t;}catch{}return s.DNS=$,s.URL=j,s}var O={randomUUID:C__default.default.randomUUID};function H(t,e,r){if(O.randomUUID&&!e&&!t)return O.randomUUID();t=t||{};let s=t.random||(t.rng||I)();if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,e){r=r||0;for(let n=0;n<16;++n)e[r+n]=s[n];return e}return _(s)}var K=H;function z(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),C__default.default.createHash("sha1").update(t).digest()}var R=z;var X=P("v5",80,R),U=X;var Z={isUUID:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?U(t,e):K(),generateSearchId:(t,e)=>`${t}#${e}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,variantId:r}}},S=Z;var q={handleException:(t,e,r)=>{e.knownError?(e.logError&&m.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(m.logException(t,e),r.status(e.status).json({...e.error,status:e.status})):(m.logException(t,e),r.status(500).json({status:500,error:i.INTERNAL_SERVER_ERROR}));},generateResponse:(t,e,r)=>({status:t,data:e,error:r}),generateError:(t,e,r=!0,s=!1)=>({status:t,error:e,knownError:r,logError:s})},f=q;var Q=async(t,e,r="GET",s={},n)=>{let o={method:r,headers:{"Content-Type":"application/json",...s}};r!=="GET"&&n&&(o.body=JSON.stringify(n));let g=`${t}${e?"/"+e:""}`;try{let a=await fetch(g,o);if(!a.ok){let u=await a.json().catch(()=>a.text());throw {status:a.status,statusText:a.statusText,error:u||{status:a.status,error:a.statusText}}}let p=await a.json();return m.logMessage("Fetch",`API call successful: URL-${g}, Status- ${a.status}`),{status:a.status,statusText:a.statusText,data:p.data}}catch(a){throw m.logError("Fetch",`API call failed: URL-${g}, Status- ${a.status||500}, Error- ${m.inspect(a.error||a)}`),{status:a.status||500,statusText:a.statusText||i.INTERNAL_SERVER_ERROR,error:a.error||{status:a.status||500,error:a.statusText||i.SOMETHING_WENT_WRONG}}}},b=Q;var F={maxTokenAge:"30 days",userPrivateKeys:"[]",userPublicKeys:"[]",anonymousPrivateKeys:"[]",anonymousPublicKeys:"[]",systemPrivateKeys:"[]",systemPublicKeys:"[]",adminPrivateKeys:"[]",adminPublicKeys:"[]"},M={allowAnonymous:!1,allowSystem:!0,allowUser:!0,allowCDN:!1},v=class{maxTokenAge;userPrivateKeys;userPublicKeys;anonymousPrivateKeys;anonymousPublicKeys;systemPrivateKeys;systemPublicKeys;adminPrivateKeys;adminPublicKeys;constructor(e=F){let{maxTokenAge:r,userPrivateKeys:s,userPublicKeys:n,anonymousPrivateKeys:o,anonymousPublicKeys:g,systemPrivateKeys:a,systemPublicKeys:p,adminPrivateKeys:u,adminPublicKeys:d}={...F,...e};this.maxTokenAge=r,this.userPrivateKeys=JSON.parse(s),this.userPublicKeys=JSON.parse(n),this.anonymousPrivateKeys=JSON.parse(o),this.anonymousPublicKeys=JSON.parse(g),this.systemPrivateKeys=JSON.parse(a),this.systemPublicKeys=JSON.parse(p),this.adminPrivateKeys=JSON.parse(u),this.adminPublicKeys=JSON.parse(d),this.logWarnings();}logWarnings(){let e=(r,s,n)=>s.length>n&&m.logWarning("AuthUtility",`More than ${n} ${r} keys provided. This is not recommended.`);e("user private",this.userPrivateKeys,3),e("user public",this.userPublicKeys,3),e("anonymous private",this.anonymousPrivateKeys,1),e("anonymous public",this.anonymousPublicKeys,3),e("system private",this.systemPrivateKeys,1),e("system public",this.systemPublicKeys,3),e("admin private",this.adminPrivateKeys,1),e("admin public",this.adminPublicKeys,3);}async createSignedJWT(e,r,s){let n=await jose.importPKCS8(r,"RS256");return await new jose.SignJWT(e).setProtectedHeader({alg:"RS256"}).setExpirationTime(s).setIssuedAt().sign(n)}async verifySignedJWT(e,r,s){for(let g=r.length-1;g>0;g--)try{let a=await jose.importSPKI(r[g],"RS256");return (await jose.jwtVerify(e,a,{clockTolerance:30,maxTokenAge:s})).payload}catch{continue}let n=await jose.importSPKI(r[0],"RS256");return (await jose.jwtVerify(e,n,{clockTolerance:30,maxTokenAge:s})).payload}async createAnonymousToken(e,r){y__default.default(this.anonymousPrivateKeys.length,i.ANONYMOUS_PRIVATE_KEY_NOT_FOUND),y__default.default(S.isUUID(e),i.INVALID_UUID);let s={id:e,type:"Anon",...r};return await this.createSignedJWT(s,this.anonymousPrivateKeys[this.anonymousPrivateKeys.length-1],this.maxTokenAge)}async verifyAnonymousToken(e){y__default.default(this.anonymousPublicKeys.length,i.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);let r=await this.verifySignedJWT(e,this.anonymousPublicKeys,this.maxTokenAge);return y__default.default(r.type==="Anon",i.INVALID_AUTH_TYPE),r}async createUserToken(e,r){y__default.default(this.userPrivateKeys.length,i.USER_PRIVATE_KEY_NOT_FOUND),y__default.default(S.isUUID(e),i.INVALID_UUID);let s={id:e,type:"User",...r};return await this.createSignedJWT(s,this.userPrivateKeys[this.userPrivateKeys.length-1],this.maxTokenAge)}async verifyUserToken(e){y__default.default(this.userPublicKeys.length,i.USER_PUBLIC_KEY_NOT_FOUND);let r=await this.verifySignedJWT(e,this.userPublicKeys,this.maxTokenAge);return y__default.default(r.type==="User",i.INVALID_AUTH_TYPE),r}async createSystemToken(e,r){y__default.default(this.systemPrivateKeys.length,i.SYSTEM_PRIVATE_KEY_NOT_FOUND);let s={id:e,type:"System",...r};return await this.createSignedJWT(s,this.systemPrivateKeys[this.systemPrivateKeys.length-1],"5 min")}async verifySystemToken(e){y__default.default(this.systemPublicKeys.length,i.USER_PUBLIC_KEY_NOT_FOUND);let r=await this.verifySignedJWT(e,this.systemPublicKeys,"5 min");return y__default.default(r.type==="System",i.INVALID_AUTH_TYPE),r}async createAdminToken(e,r,s){y__default.default(this.adminPrivateKeys.length,i.ADMIN_PRIVATE_KEY_NOT_FOUND),y__default.default(S.isEmail(e),i.INVALID_EMAIL),y__default.default(S.isURL(r),i.INVALID_VERIFIER);let n={email:e,type:"Admin",verifier:r,...s};return await this.createSignedJWT(n,this.adminPrivateKeys[this.adminPrivateKeys.length-1],this.maxTokenAge)}async verifyAdminToken(e,r,s){y__default.default(this.adminPublicKeys.length,i.ADMIN_PUBLIC_KEY_NOT_FOUND);let n=await this.verifySignedJWT(e,this.adminPublicKeys,this.maxTokenAge);if(y__default.default(n.type==="Admin",i.INVALID_AUTH_TYPE),s){let o=await b(n.verifier,"","POST",{},{token:e,permissions:r});if(y__default.default(o.data.isTokenValid===!0,i.INVALID_TOKEN),o.data.hasPermissions!==!0)throw f.generateError(403,i.INVALID_PERMISSIONS)}return n}AuthMiddleware(e=M,r=[]){let{allowAnonymous:s,allowSystem:n,allowUser:o,allowCDN:g}={...M,...e};return async(a,p,u)=>{try{let[d,N]=a.get("Authorization")?.split(" ")||[];if(!N)throw new Error(i.INVALID_TOKEN);let T;switch(d){case"Anon":if(!s)throw f.generateError(403,i.ANONYMOUS_SESSION_NOT_ALLOWED);T=await this.verifyAnonymousToken(N);break;case"User":if(!o)throw f.generateError(403,i.USER_SESSION_NOT_ALLOWED);T=await this.verifyUserToken(N);break;case"System":if(!n)throw f.generateError(403,i.SYSTEM_SESSION_NOT_ALLOWED);T=await this.verifySystemToken(N),m.logMessage("AuthMiddleware",`System Name - ${T.id}`);break;case"Admin":T=await this.verifyAdminToken(N,r,!0),m.logMessage("AuthMiddleware",`Admin - ${T.email}`);break;case"CDN":if(!g)throw f.generateError(403,i.CDN_SESSION_NOT_ALLOWED);y__default.default(["E3CQMOP5FX6KD1","E3TNCKKZ3FOX9W"].includes(N),i.INVALID_TOKEN),m.logMessage("AuthMiddleware",`CDN DistributionId - ${N}`);break;default:throw f.generateError(403,i.INVALID_AUTH_TYPE)}p.locals.auth={authType:d,token:N,...T},u();}catch(d){m.logError("AuthMiddleware",d),f.handleException("AuthMiddleware",f.generateError(401,d.error||i.TOKEN_EXPIRED,!0),p);}}}},ot=v;exports.DefaultAuthMiddlewareConfig=M;exports.DefaultAuthUtilityConfig=F;exports.default=ot;//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/enums/ErrorTypes.ts","../../src/Logger/index.ts","../../node_modules/uuid/dist/esm-node/rng.js","../../node_modules/uuid/dist/esm-node/regex.js","../../node_modules/uuid/dist/esm-node/validate.js","../../node_modules/uuid/dist/esm-node/stringify.js","../../node_modules/uuid/dist/esm-node/parse.js","../../node_modules/uuid/dist/esm-node/v35.js","../../node_modules/uuid/dist/esm-node/native.js","../../node_modules/uuid/dist/esm-node/v4.js","../../node_modules/uuid/dist/esm-node/sha1.js","../../node_modules/uuid/dist/esm-node/v5.js","../../src/Utils/index.ts","../../src/Utils/response.ts","../../src/Auth/index.ts","../../src/Utils/fetch.ts"],"names":["ErrorTypes_default","Logger","functionName","error","message","errorMessage","context","util","Logger_default","rnds8Pool","poolPtr","rng","crypto","regex_default","validate","uuid","validate_default","byteToHex","i","unsafeStringify","arr","offset","parse","v","parse_default","stringToBytes","str","bytes","DNS","URL","v35","name","version","hashfunc","generateUUID","value","namespace","buf","_namespace","native_default","v4","options","rnds","v4_default","sha1","sha1_default","v5","v5_default","Utils","key","variantId","searchId","Utils_default","ResponseUtility","res","status","data","knownError","logError","response_default","Fetch","baseURL","endpoint","method","headers","payload","completeURL","response","errorBody","body","err","fetch_default","DefaultAuthUtilityConfig","DefaultAuthMiddlewareConfig","AuthUtility","config","maxTokenAge","userPrivateKeys","userPublicKeys","anonymousPrivateKeys","anonymousPublicKeys","systemPrivateKeys","systemPublicKeys","adminPrivateKeys","adminPublicKeys","warn","type","keys","limit","privateKeyString","expiration","privateKey","importPKCS8","SignJWT","token","publicKeyString","publicKey","importSPKI","jwtVerify","id","additionalData","assert","email","verifier","permissions","authenticate","allowAnonymous","allowSystem","allowUser","allowCDN","req","next","authType","Auth_default"],"mappings":"uWAAA,IAAOA,CAAAA,CAAQ,MAAO,CAAA,MAAA,CAAO,CACzB,YAAA,CAAc,cACd,CAAA,aAAA,CAAe,eACf,CAAA,aAAA,CAAe,eACf,CAAA,aAAA,CAAe,eACf,CAAA,gBAAA,CAAkB,kBAClB,CAAA,mBAAA,CAAqB,qBACrB,CAAA,iBAAA,CAAmB,4BACnB,CAAA,0BAAA,CAA4B,4BAC5B,CAAA,yBAA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r\n INVALID_UUID: \"Invalid UUID\",\r\n INVALID_EMAIL: \"Invalid Email\",\r\n INVALID_TOKEN: \"Invalid Token\",\r\n TOKEN_EXPIRED: \"Token Expired\",\r\n INVALID_VERIFIER: \"Invalid Verifier\",\r\n INVALID_PERMISSIONS: \"Invalid Permissions\",\r\n INVALID_AUTH_TYPE: \"Invalid Authorization Type\",\r\n USER_PRIVATE_KEY_NOT_FOUND: \"User Private Key Not Found\",\r\n USER_PUBLIC_KEY_NOT_FOUND: \"User Public Key Not Found\",\r\n ANONYMOUS_PRIVATE_KEY_NOT_FOUND: \"Anonymous Private Key Not Found\",\r\n ANONYMOUS_PUBLIC_KEY_NOT_FOUND: \"Anonymous Public Key Not Found\",\r\n SYSTEM_PRIVATE_KEY_NOT_FOUND: \"System Private Key Not Found\",\r\n SYSTEM_PUBLIC_KEY_NOT_FOUND: \"System Public Key Not Found\",\r\n ADMIN_PRIVATE_KEY_NOT_FOUND: \"Admin Private Key Not Found\",\r\n ADMIN_PUBLIC_KEY_NOT_FOUND: \"Admin Public Key Not Found\",\r\n SECRET_TOKEN_NOT_FOUND: \"Secret Token Not Found\",\r\n ANONYMOUS_SESSION_NOT_ALLOWED: \"Anonymous Session Not Allowed\",\r\n USER_SESSION_NOT_ALLOWED: \"User Session Not Allowed\",\r\n SYSTEM_SESSION_NOT_ALLOWED: \"System Session Not Allowed\",\r\n CDN_SESSION_NOT_ALLOWED: \"CDN Session Not Allowed\",\r\n INTERNAL_SERVER_ERROR: \"Internal Server Error\",\r\n SOMETHING_WENT_WRONG: 'Something went wrong'\r\n})","import util from 'node:util';\r\nconst Logger = {\r\n logException: (functionName: string, error: any) => {\r\n console.error(`Exception Occurred in Function: ${functionName}, Error: ${Logger.inspect(error)}`);\r\n },\r\n\r\n logError: (functionName: string, error: any) => {\r\n console.error(`Error Occurred in Function: ${functionName}, Error: ${Logger.inspect(error)}`);\r\n },\r\n\r\n logWarning: (functionName: string, message: any) => {\r\n console.warn(`Warning in Function: ${functionName} - ${Logger.inspect(message)}`);\r\n },\r\n\r\n logMessage: (functionName: string, message: any) => {\r\n console.log(`Message in Function: ${functionName} - ${Logger.inspect(message)}`);\r\n },\r\n\r\n logInvalidPayload: (functionName: string, errorMessage: string) => {\r\n console.error(`Invalid Payload received for Function: ${functionName}, Error: ${Logger.inspect(errorMessage)}`);\r\n },\r\n\r\n inspect: (context: any) => {\r\n return (typeof context === \"string\" ? context : util.inspect(context));\r\n }\r\n}\r\n\r\nexport default Logger;","import crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","import { unsafeStringify } from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","import crypto from 'crypto';\nexport default {\n randomUUID: crypto.randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import crypto from 'crypto';\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return crypto.createHash('sha1').update(bytes).digest();\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nconst v5 = v35('v5', 0x50, sha1);\nexport default v5;","import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';\r\n\r\nconst Utils = {\r\n isUUID: (value: string): boolean => {\r\n 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;\r\n return uuidRegex.test(value);\r\n },\r\n\r\n isEmail: (value: string): boolean => {\r\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\r\n return emailRegex.test(value);\r\n },\r\n\r\n isURL: (value: string): boolean => {\r\n const urlRegex = /^(http|https):\\/\\/[^ \"]+$/;\r\n return urlRegex.test(value);\r\n },\r\n \r\n generateUUID: (value?: string, namespace?: string) => {\r\n if(namespace && value){\r\n return uuidv5(value, namespace);\r\n }\r\n return uuidv4();\r\n },\r\n\r\n generateSearchId: (key: string, variantId: string) => {\r\n return `${key}#${variantId}`;\r\n },\r\n\r\n getKeyfromSearchId: (searchId: string) => {\r\n const [key, variantId] = searchId.split('#');\r\n return {\r\n key,\r\n variantId\r\n }\r\n },\r\n}\r\n\r\nexport default Utils;\r\n","import ErrorTypes from \"../enums/ErrorTypes\";\r\nimport Logger from \"../Logger\";\r\n\r\nexport const ResponseUtility = {\r\n handleException: (functionName: string, error: any, res: any) => {\r\n if (error.knownError) {\r\n error.logError && Logger.logError(functionName, error);\r\n res.status(error.status).json({\r\n status: error.status,\r\n error: error.error\r\n });\r\n } else if(error.status && error.error) {\r\n Logger.logException(functionName, error);\r\n res.status(error.status).json({\r\n ...error.error,\r\n status: error.status,\r\n });\r\n } else {\r\n Logger.logException(functionName, error);\r\n res.status(500).json({\r\n status: 500,\r\n error: ErrorTypes.INTERNAL_SERVER_ERROR\r\n })\r\n }\r\n },\r\n\r\n generateResponse: (status: number, data?: any, error?: string) => {\r\n return {\r\n status,\r\n data,\r\n error\r\n }\r\n },\r\n\r\n generateError: (status: number, error: string, knownError: Boolean = true, logError: boolean = false) => {\r\n return {\r\n status,\r\n error,\r\n knownError,\r\n logError\r\n }\r\n }\r\n}\r\n\r\nexport default ResponseUtility;","import { importPKCS8, importSPKI, jwtVerify, SignJWT} from 'jose';\r\nimport ErrorTypes from '../enums/ErrorTypes';\r\nimport Logger from '../Logger';\r\nimport Utils from '../Utils';\r\nimport ResponseUtility from '../Utils/response';\r\nimport assert from 'assert';\r\nimport Fetch from '../Utils/fetch';\r\n\r\ntype StringifiedJSONArray = string;\r\n\r\nexport interface AuthUtilityConfig {\r\n maxTokenAge: string;\r\n userPrivateKeys: StringifiedJSONArray;\r\n userPublicKeys: StringifiedJSONArray;\r\n anonymousPrivateKeys: StringifiedJSONArray;\r\n anonymousPublicKeys: StringifiedJSONArray;\r\n systemPrivateKeys: StringifiedJSONArray;\r\n systemPublicKeys: StringifiedJSONArray;\r\n adminPrivateKeys: StringifiedJSONArray;\r\n adminPublicKeys: StringifiedJSONArray;\r\n}\r\n\r\nexport const DefaultAuthUtilityConfig: Readonly<AuthUtilityConfig> = {\r\n maxTokenAge: '30 days',\r\n userPrivateKeys: '[]',\r\n userPublicKeys: '[]',\r\n anonymousPrivateKeys: '[]',\r\n anonymousPublicKeys: '[]',\r\n systemPrivateKeys: '[]',\r\n systemPublicKeys: '[]',\r\n adminPrivateKeys: '[]',\r\n adminPublicKeys: '[]',\r\n};\r\n\r\nexport type AuthTokenType = 'Anon' | 'User' | 'System' | 'Admin' | 'CDN';\r\n\r\nexport interface AuthMiddlewareConfig {\r\n allowAnonymous: boolean;\r\n allowSystem: boolean;\r\n allowUser: boolean;\r\n allowCDN: boolean;\r\n}\r\n\r\nexport const DefaultAuthMiddlewareConfig: Readonly<AuthMiddlewareConfig> = {\r\n allowAnonymous: false,\r\n allowSystem: true,\r\n allowUser: true,\r\n allowCDN: false\r\n};\r\n\r\n/**\r\n * A utility class for JWT authentication and authorization.\r\n */\r\nclass AuthUtility {\r\n private maxTokenAge: string;\r\n private userPrivateKeys: string[];\r\n private userPublicKeys: string[];\r\n private anonymousPrivateKeys: string[];\r\n private anonymousPublicKeys: string[];\r\n private systemPrivateKeys: string[];\r\n private systemPublicKeys: string[];\r\n private adminPrivateKeys: string[];\r\n private adminPublicKeys: string[];\r\n\r\n /**\r\n * Initializes the AuthUtility class with a configuration.\r\n * @param config The configuration for the utility (optional).\r\n */\r\n constructor(config: Partial<AuthUtilityConfig> = DefaultAuthUtilityConfig) {\r\n const {\r\n maxTokenAge,\r\n userPrivateKeys,\r\n userPublicKeys,\r\n anonymousPrivateKeys,\r\n anonymousPublicKeys,\r\n systemPrivateKeys,\r\n systemPublicKeys,\r\n adminPrivateKeys,\r\n adminPublicKeys,\r\n } = { ...DefaultAuthUtilityConfig, ...config };\r\n\r\n this.maxTokenAge = maxTokenAge;\r\n\r\n this.userPrivateKeys = JSON.parse(userPrivateKeys);\r\n this.userPublicKeys = JSON.parse(userPublicKeys);\r\n\r\n this.anonymousPrivateKeys = JSON.parse(anonymousPrivateKeys);\r\n this.anonymousPublicKeys = JSON.parse(anonymousPublicKeys);\r\n\r\n this.systemPrivateKeys = JSON.parse(systemPrivateKeys);\r\n this.systemPublicKeys = JSON.parse(systemPublicKeys);\r\n\r\n this.adminPrivateKeys = JSON.parse(adminPrivateKeys);\r\n this.adminPublicKeys = JSON.parse(adminPublicKeys);\r\n\r\n this.logWarnings();\r\n }\r\n\r\n /**\r\n * Logs warnings if the number of keys exceeds recommended limits.\r\n */\r\n private logWarnings() {\r\n const warn = (type: string, keys: string[], limit: number) =>\r\n keys.length > limit &&\r\n Logger.logWarning(\r\n 'AuthUtility',\r\n `More than ${limit} ${type} keys provided. This is not recommended.`\r\n );\r\n\r\n warn('user private', this.userPrivateKeys, 3);\r\n warn('user public', this.userPublicKeys, 3);\r\n warn('anonymous private', this.anonymousPrivateKeys, 1);\r\n warn('anonymous public', this.anonymousPublicKeys, 3);\r\n warn('system private', this.systemPrivateKeys, 1);\r\n warn('system public', this.systemPublicKeys, 3);\r\n warn('admin private', this.adminPrivateKeys, 1);\r\n warn('admin public', this.adminPublicKeys, 3);\r\n }\r\n\r\n private async createSignedJWT(payload: any, privateKeyString: string, expiration: string){\r\n const privateKey = await importPKCS8(privateKeyString, 'RS256');\r\n const token = await new SignJWT(payload)\r\n .setProtectedHeader({ alg: 'RS256' })\r\n .setExpirationTime(expiration)\r\n .setIssuedAt()\r\n .sign(privateKey);\r\n\r\n return token;\r\n }\r\n\r\n private async verifySignedJWT(token: string, publicKeyString: string[], expiration: string){\r\n for(let i = publicKeyString.length - 1; i > 0 ; i--){\r\n try { \r\n const publicKey = await importSPKI(publicKeyString[i], 'RS256')\r\n const jwt = await jwtVerify(token, publicKey, { clockTolerance: 30, maxTokenAge: expiration });\r\n return jwt.payload;\r\n } catch (error) {\r\n // Try with the next oldest key\r\n continue;\r\n }\r\n }\r\n\r\n const publicKey = await importSPKI(publicKeyString[0], 'RS256')\r\n const jwt = await jwtVerify(token, publicKey, { clockTolerance: 30, maxTokenAge: expiration });\r\n return jwt.payload;\r\n }\r\n\r\n \r\n /**\r\n * Creates an anonymous token with the given ID and additional data.\r\n *\r\n * @param id - The unique identifier for the token. Must be a valid UUID.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no anonymous private keys are found or if the ID is not a valid UUID.\r\n */\r\n async createAnonymousToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.anonymousPrivateKeys.length, ErrorTypes.ANONYMOUS_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n const payload = {\r\n id,\r\n type: 'Anon',\r\n ...additionalData\r\n };\r\n\r\n return await this.createSignedJWT(payload, this.anonymousPrivateKeys[this.anonymousPrivateKeys.length - 1], this.maxTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies an anonymous token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no anonymous public keys are found or if the token type is invalid.\r\n */\r\n async verifyAnonymousToken(token: string){\r\n assert(this.anonymousPublicKeys.length, ErrorTypes.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.anonymousPublicKeys, this.maxTokenAge);\r\n assert(payload.type === 'Anon', ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for a user.\r\n *\r\n * @param id - The UUID of the user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token as a string.\r\n * @throws Will throw an error if no user private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createUserToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.userPrivateKeys.length, ErrorTypes.USER_PRIVATE_KEY_NOT_FOUND);\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n\r\n const payload = {\r\n id,\r\n type: 'User',\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.userPrivateKeys[this.userPrivateKeys.length - 1], this.maxTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided user token by checking its signature and payload.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token if valid.\r\n * @throws Will throw an error if no user public keys are found or if the token type is invalid.\r\n */\r\n async verifyUserToken(token: string){\r\n assert(this.userPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload =await this.verifySignedJWT(token, this.userPublicKeys, this.maxTokenAge);\r\n assert(payload.type === 'User', ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT (JSON Web Token) for a system with the given ID and optional additional data.\r\n *\r\n * @param id - The unique identifier for the system.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no system private keys are found.\r\n */\r\n async createSystemToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.systemPrivateKeys.length, ErrorTypes.SYSTEM_PRIVATE_KEY_NOT_FOUND);\r\n\r\n const payload = {\r\n id,\r\n type: 'System',\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.systemPrivateKeys[this.systemPrivateKeys.length - 1], '5 min');\r\n }\r\n\r\n /**\r\n * Verifies a system token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no system public keys are found or if the token type is not 'System'.\r\n */\r\n async verifySystemToken(token: string){\r\n assert(this.systemPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.systemPublicKeys, '5 min');\r\n assert(payload.type === 'System', ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for an admin user.\r\n *\r\n * @param email - The email of the admin user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token string.\r\n * @throws Will throw an error if no admin private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createAdminToken(email: string, verifier: string, additionalData?: object): Promise<string> {\r\n assert(this.adminPrivateKeys.length, ErrorTypes.ADMIN_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isEmail(email), ErrorTypes.INVALID_EMAIL);\r\n assert(Utils.isURL(verifier), ErrorTypes.INVALID_VERIFIER);\r\n const payload = {\r\n email,\r\n type: 'Admin',\r\n verifier: verifier,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.adminPrivateKeys[this.adminPrivateKeys.length - 1], this.maxTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided admin token by checking its signature and payload.\r\n * Ensures that the token is signed with one of the known admin public keys\r\n * and that the payload type is 'Admin'.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @param permissions - The permissions required for the admin user.\r\n * @param authenticate - Whether to authenticate the token with the verifier.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no admin public keys are found or if the token is invalid or if the admin doesn't have proper permissions.\r\n */\r\n async verifyAdminToken(token: string, permissions: string[], authenticate: boolean){\r\n assert(this.adminPublicKeys.length, ErrorTypes.ADMIN_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.adminPublicKeys, this.maxTokenAge);\r\n assert(payload.type === 'Admin', ErrorTypes.INVALID_AUTH_TYPE);\r\n\r\n if(authenticate) {\r\n const response = await Fetch(payload.verifier as string, '', 'POST', {}, { token, permissions });\r\n assert(response.data.isTokenValid === true, ErrorTypes.INVALID_TOKEN);\r\n \r\n if(response.data.hasPermissions !== true){\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_PERMISSIONS)\r\n }\r\n }\r\n\r\n return payload;\r\n }\r\n\r\n /**\r\n * Middleware function to handle authentication based on different token types.\r\n * It verifies the token and sets the authentication details in the response locals.\r\n *\r\n * @param {Partial<AuthMiddlewareConfig>} [config=DefaultAuthMiddlewareConfig] - Configuration object to customize the middleware behavior.\r\n * @returns Middleware function to handle authentication.\r\n */\r\n AuthMiddleware(config: Partial<AuthMiddlewareConfig> = DefaultAuthMiddlewareConfig, permissions: string[] = []) {\r\n const { allowAnonymous, allowSystem, allowUser, allowCDN } = { ...DefaultAuthMiddlewareConfig, ...config };\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n if (!token) throw new Error(ErrorTypes.INVALID_TOKEN);\r\n\r\n let payload;\r\n switch (authType as AuthTokenType) {\r\n case 'Anon':\r\n if (!allowAnonymous) throw ResponseUtility.generateError(403, ErrorTypes.ANONYMOUS_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyAnonymousToken(token);\r\n break;\r\n case 'User':\r\n if (!allowUser) throw ResponseUtility.generateError(403, ErrorTypes.USER_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyUserToken(token);\r\n break;\r\n case 'System':\r\n if (!allowSystem) throw ResponseUtility.generateError(403, ErrorTypes.SYSTEM_SESSION_NOT_ALLOWED);\r\n payload = await this.verifySystemToken(token);\r\n Logger.logMessage('AuthMiddleware', `System Name - ${payload.id}`);\r\n break;\r\n case 'Admin':\r\n payload = await this.verifyAdminToken(token, permissions, true);\r\n Logger.logMessage('AuthMiddleware', `Admin - ${payload.email}`);\r\n break;\r\n case 'CDN':\r\n if (!allowCDN) throw ResponseUtility.generateError(403, ErrorTypes.CDN_SESSION_NOT_ALLOWED);\r\n assert(['E3CQMOP5FX6KD1', 'E3TNCKKZ3FOX9W'].includes(token), ErrorTypes.INVALID_TOKEN);\r\n Logger.logMessage('AuthMiddleware', `CDN DistributionId - ${token}`);\r\n break;\r\n default:\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_AUTH_TYPE);\r\n }\r\n\r\n res.locals.auth = { authType, token, ...payload };\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthMiddleware',\r\n ResponseUtility.generateError(401, error.error || ErrorTypes.TOKEN_EXPIRED, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n}\r\n\r\nexport default AuthUtility;\r\n\r\n","\"use client\";\r\n\r\nimport ErrorTypes from \"../enums/ErrorTypes\";\r\nimport Logger from \"../Logger\";\r\n\r\nexport type ErrorType = {\r\n status: number;\r\n statusText: string;\r\n error: any;\r\n};\r\n\r\nexport type SuccessType = {\r\n status: number;\r\n statusText: string;\r\n data: any;\r\n};\r\n\r\n/**\r\n * Makes an HTTP request to the specified endpoint using the provided parameters.\r\n *\r\n * @param {string} baseURL - The base URL of the API.\r\n * @param {string} endpoint - The specific endpoint to call.\r\n * @param {'GET' | 'POST' | 'PATCH' | 'DELETE'} [method='GET'] - The HTTP method to use for the request.\r\n * @param {Record<string, string>} [headers={}] - Additional headers to include in the request.\r\n * @param {any} [payload] - The payload to send with the request, if applicable.\r\n * @returns {Promise<SuccessType>} - A promise that resolves to the response data if the request is successful.\r\n * @throws {ErrorType} - Throws an error if the request fails.\r\n */\r\nconst Fetch = async (\r\n baseURL: string,\r\n endpoint: string,\r\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' = 'GET',\r\n headers: Record<string, string> = {},\r\n payload?: any,\r\n): Promise<SuccessType> => {\r\n const options: RequestInit = {\r\n method,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n ...headers,\r\n },\r\n };\r\n\r\n if (method !== 'GET' && payload) {\r\n options.body = JSON.stringify(payload);\r\n }\r\n\r\n const completeURL = `${baseURL}${endpoint ? ('/' + endpoint) : ''}`\r\n try {\r\n const response: any = await fetch(completeURL, options);\r\n\r\n if (!response.ok) {\r\n const errorBody: any = await response.json().catch(() => response.text());\r\n\r\n throw {\r\n status: response.status,\r\n statusText: response.statusText,\r\n error: errorBody ? errorBody : {\r\n status: response.status,\r\n error: response.statusText,\r\n }\r\n } as ErrorType;\r\n }\r\n\r\n const body = await response.json();\r\n\r\n Logger.logMessage('Fetch', `API call successful: URL-${completeURL}, Status- ${response.status}`);\r\n return {\r\n status: response.status,\r\n statusText: response.statusText,\r\n data: body.data,\r\n } as SuccessType;\r\n } catch (err: any) {\r\n \r\n Logger.logError('Fetch', `API call failed: URL-${completeURL}, Status- ${err.status || 500}, Error- ${Logger.inspect(err.error || err)}`);\r\n throw {\r\n status: err.status || 500,\r\n statusText: err.statusText || ErrorTypes.INTERNAL_SERVER_ERROR,\r\n error: err.error || {\r\n status: err.status || 500,\r\n error: err.statusText || ErrorTypes.SOMETHING_WENT_WRONG,\r\n }\r\n } as ErrorType;\r\n }\r\n};\r\n\r\nexport default Fetch;\r\n"]}
@@ -0,0 +1,2 @@
1
+ import {b,a,e,d,c}from'../chunk-T6YCHB3K.mjs';import {importPKCS8,SignJWT,importSPKI,jwtVerify}from'jose';import r from'assert';var N={maxTokenAge:"30 days",userPrivateKeys:"[]",userPublicKeys:"[]",anonymousPrivateKeys:"[]",anonymousPublicKeys:"[]",systemPrivateKeys:"[]",systemPublicKeys:"[]",adminPrivateKeys:"[]",adminPublicKeys:"[]"},p={allowAnonymous:!1,allowSystem:!0,allowUser:!0,allowCDN:!1},A=class{maxTokenAge;userPrivateKeys;userPublicKeys;anonymousPrivateKeys;anonymousPublicKeys;systemPrivateKeys;systemPublicKeys;adminPrivateKeys;adminPublicKeys;constructor(e=N){let{maxTokenAge:t,userPrivateKeys:s,userPublicKeys:a,anonymousPrivateKeys:o,anonymousPublicKeys:l,systemPrivateKeys:g,systemPublicKeys:h,adminPrivateKeys:d,adminPublicKeys:u}={...N,...e};this.maxTokenAge=t,this.userPrivateKeys=JSON.parse(s),this.userPublicKeys=JSON.parse(a),this.anonymousPrivateKeys=JSON.parse(o),this.anonymousPublicKeys=JSON.parse(l),this.systemPrivateKeys=JSON.parse(g),this.systemPublicKeys=JSON.parse(h),this.adminPrivateKeys=JSON.parse(d),this.adminPublicKeys=JSON.parse(u),this.logWarnings();}logWarnings(){let e=(t,s,a)=>s.length>a&&c.logWarning("AuthUtility",`More than ${a} ${t} keys provided. This is not recommended.`);e("user private",this.userPrivateKeys,3),e("user public",this.userPublicKeys,3),e("anonymous private",this.anonymousPrivateKeys,1),e("anonymous public",this.anonymousPublicKeys,3),e("system private",this.systemPrivateKeys,1),e("system public",this.systemPublicKeys,3),e("admin private",this.adminPrivateKeys,1),e("admin public",this.adminPublicKeys,3);}async createSignedJWT(e,t,s){let a=await importPKCS8(t,"RS256");return await new SignJWT(e).setProtectedHeader({alg:"RS256"}).setExpirationTime(s).setIssuedAt().sign(a)}async verifySignedJWT(e,t,s){for(let l=t.length-1;l>0;l--)try{let g=await importSPKI(t[l],"RS256");return (await jwtVerify(e,g,{clockTolerance:30,maxTokenAge:s})).payload}catch{continue}let a=await importSPKI(t[0],"RS256");return (await jwtVerify(e,a,{clockTolerance:30,maxTokenAge:s})).payload}async createAnonymousToken(e,t){r(this.anonymousPrivateKeys.length,b.ANONYMOUS_PRIVATE_KEY_NOT_FOUND),r(a.isUUID(e),b.INVALID_UUID);let s={id:e,type:"Anon",...t};return await this.createSignedJWT(s,this.anonymousPrivateKeys[this.anonymousPrivateKeys.length-1],this.maxTokenAge)}async verifyAnonymousToken(e){r(this.anonymousPublicKeys.length,b.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.anonymousPublicKeys,this.maxTokenAge);return r(t.type==="Anon",b.INVALID_AUTH_TYPE),t}async createUserToken(e,t){r(this.userPrivateKeys.length,b.USER_PRIVATE_KEY_NOT_FOUND),r(a.isUUID(e),b.INVALID_UUID);let s={id:e,type:"User",...t};return await this.createSignedJWT(s,this.userPrivateKeys[this.userPrivateKeys.length-1],this.maxTokenAge)}async verifyUserToken(e){r(this.userPublicKeys.length,b.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.userPublicKeys,this.maxTokenAge);return r(t.type==="User",b.INVALID_AUTH_TYPE),t}async createSystemToken(e,t){r(this.systemPrivateKeys.length,b.SYSTEM_PRIVATE_KEY_NOT_FOUND);let s={id:e,type:"System",...t};return await this.createSignedJWT(s,this.systemPrivateKeys[this.systemPrivateKeys.length-1],"5 min")}async verifySystemToken(e){r(this.systemPublicKeys.length,b.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.systemPublicKeys,"5 min");return r(t.type==="System",b.INVALID_AUTH_TYPE),t}async createAdminToken(e,t,s){r(this.adminPrivateKeys.length,b.ADMIN_PRIVATE_KEY_NOT_FOUND),r(a.isEmail(e),b.INVALID_EMAIL),r(a.isURL(t),b.INVALID_VERIFIER);let a$1={email:e,type:"Admin",verifier:t,...s};return await this.createSignedJWT(a$1,this.adminPrivateKeys[this.adminPrivateKeys.length-1],this.maxTokenAge)}async verifyAdminToken(e$1,t,s){r(this.adminPublicKeys.length,b.ADMIN_PUBLIC_KEY_NOT_FOUND);let a=await this.verifySignedJWT(e$1,this.adminPublicKeys,this.maxTokenAge);if(r(a.type==="Admin",b.INVALID_AUTH_TYPE),s){let o=await e(a.verifier,"","POST",{},{token:e$1,permissions:t});if(r(o.data.isTokenValid===!0,b.INVALID_TOKEN),o.data.hasPermissions!==!0)throw d.generateError(403,b.INVALID_PERMISSIONS)}return a}AuthMiddleware(e=p,t=[]){let{allowAnonymous:s,allowSystem:a,allowUser:o,allowCDN:l}={...p,...e};return async(g,h,d$1)=>{try{let[u,y]=g.get("Authorization")?.split(" ")||[];if(!y)throw new Error(b.INVALID_TOKEN);let m;switch(u){case"Anon":if(!s)throw d.generateError(403,b.ANONYMOUS_SESSION_NOT_ALLOWED);m=await this.verifyAnonymousToken(y);break;case"User":if(!o)throw d.generateError(403,b.USER_SESSION_NOT_ALLOWED);m=await this.verifyUserToken(y);break;case"System":if(!a)throw d.generateError(403,b.SYSTEM_SESSION_NOT_ALLOWED);m=await this.verifySystemToken(y),c.logMessage("AuthMiddleware",`System Name - ${m.id}`);break;case"Admin":m=await this.verifyAdminToken(y,t,!0),c.logMessage("AuthMiddleware",`Admin - ${m.email}`);break;case"CDN":if(!l)throw d.generateError(403,b.CDN_SESSION_NOT_ALLOWED);r(["E3CQMOP5FX6KD1","E3TNCKKZ3FOX9W"].includes(y),b.INVALID_TOKEN),c.logMessage("AuthMiddleware",`CDN DistributionId - ${y}`);break;default:throw d.generateError(403,b.INVALID_AUTH_TYPE)}h.locals.auth={authType:u,token:y,...m},d$1();}catch(u){c.logError("AuthMiddleware",u),d.handleException("AuthMiddleware",d.generateError(401,u.error||b.TOKEN_EXPIRED,!0),h);}}}},L=A;export{p as DefaultAuthMiddlewareConfig,N as DefaultAuthUtilityConfig,L as default};//# sourceMappingURL=index.mjs.map
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/Auth/index.ts"],"names":["DefaultAuthUtilityConfig","DefaultAuthMiddlewareConfig","AuthUtility","config","maxTokenAge","userPrivateKeys","userPublicKeys","anonymousPrivateKeys","anonymousPublicKeys","systemPrivateKeys","systemPublicKeys","adminPrivateKeys","adminPublicKeys","warn","type","keys","limit","Logger_default","payload","privateKeyString","expiration","privateKey","importPKCS8","SignJWT","token","publicKeyString","i","publicKey","importSPKI","jwtVerify","id","additionalData","assert","ErrorTypes_default","Utils_default","email","verifier","permissions","authenticate","response","fetch_default","response_default","allowAnonymous","allowSystem","allowUser","allowCDN","req","res","next","authType","error","Auth_default"],"mappings":"gIAsBaA,IAAAA,CAAAA,CAAwD,CACnE,WAAA,CAAa,SACb,CAAA,eAAA,CAAiB,KACjB,cAAgB,CAAA,IAAA,CAChB,oBAAsB,CAAA,IAAA,CACtB,mBAAqB,CAAA,IAAA,CACrB,kBAAmB,IACnB,CAAA,gBAAA,CAAkB,IAClB,CAAA,gBAAA,CAAkB,IAClB,CAAA,eAAA,CAAiB,IACnB,CAWaC,CAAAA,CAAAA,CAA8D,CACzE,cAAA,CAAgB,CAChB,CAAA,CAAA,WAAA,CAAa,GACb,SAAW,CAAA,CAAA,CAAA,CACX,QAAU,CAAA,CAAA,CACZ,CAKMC,CAAAA,CAAAA,CAAN,KAAkB,CACR,WAAA,CACA,eACA,CAAA,cAAA,CACA,oBACA,CAAA,mBAAA,CACA,kBACA,gBACA,CAAA,gBAAA,CACA,eAMR,CAAA,WAAA,CAAYC,CAAqCH,CAAAA,CAAAA,CAA0B,CACzE,GAAM,CACJ,WAAAI,CAAAA,CAAAA,CACA,eAAAC,CAAAA,CAAAA,CACA,eAAAC,CACA,CAAA,oBAAA,CAAAC,CACA,CAAA,mBAAA,CAAAC,CAC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BC,EAAQ,EAAE,CAAA,CAAE,CACjE,CAAA,MACF,IAAK,OAAA,CACHA,EAAU,MAAM,IAAA,CAAK,gBAAiBM,CAAAA,CAAAA,CAAOa,CAAa,CAAA,CAAA,CAAI,EAC9DpB,CAAO,CAAA,UAAA,CAAW,gBAAkB,CAAA,CAAA,QAAA,EAAWC,CAAQ,CAAA,KAAK,EAAE,CAC9D,CAAA,MACF,IAAK,KAAA,CACH,GAAI,CAAC2B,EAAU,MAAMJ,CAAAA,CAAgB,aAAc,CAAA,GAAA,CAAKR,CAAW,CAAA,uBAAuB,EAC1FD,CAAO,CAAA,CAAC,gBAAkB,CAAA,gBAAgB,CAAE,CAAA,QAAA,CAASR,CAAK,CAAGS,CAAAA,CAAAA,CAAW,aAAa,CAAA,CACrFhB,CAAO,CAAA,UAAA,CAAW,iBAAkB,CAAwBO,qBAAAA,EAAAA,CAAK,CAAE,CAAA,CAAA,CACnE,MACF,QACE,MAAMiB,CAAgB,CAAA,aAAA,CAAc,GAAKR,CAAAA,CAAAA,CAAW,iBAAiB,CACzE,CAEAc,CAAI,CAAA,MAAA,CAAO,IAAO,CAAA,CAAE,QAAAE,CAAAA,CAAAA,CAAU,MAAAzB,CAAO,CAAA,GAAGN,CAAQ,CAAA,CAChD8B,GAAK,GACP,OAASE,CAAY,CAAA,CACnBjC,CAAO,CAAA,QAAA,CAAS,gBAAkBiC,CAAAA,CAAK,EACvCT,CAAgB,CAAA,eAAA,CACd,gBACAA,CAAAA,CAAAA,CAAgB,aAAc,CAAA,GAAA,CAAKS,EAAM,KAASjB,EAAAA,CAAAA,CAAW,aAAe,CAAA,CAAA,CAAI,CAChFc,CAAAA,CACF,EACF,CACF,CACF,CACF,CAAA,CAEOI,CAAQjD,CAAAA","file":"index.mjs","sourcesContent":["import { importPKCS8, importSPKI, jwtVerify, SignJWT} from 'jose';\r\nimport ErrorTypes from '../enums/ErrorTypes';\r\nimport Logger from '../Logger';\r\nimport Utils from '../Utils';\r\nimport ResponseUtility from '../Utils/response';\r\nimport assert from 'assert';\r\nimport Fetch from '../Utils/fetch';\r\n\r\ntype StringifiedJSONArray = string;\r\n\r\nexport interface AuthUtilityConfig {\r\n maxTokenAge: string;\r\n userPrivateKeys: StringifiedJSONArray;\r\n userPublicKeys: StringifiedJSONArray;\r\n anonymousPrivateKeys: StringifiedJSONArray;\r\n anonymousPublicKeys: StringifiedJSONArray;\r\n systemPrivateKeys: StringifiedJSONArray;\r\n systemPublicKeys: StringifiedJSONArray;\r\n adminPrivateKeys: StringifiedJSONArray;\r\n adminPublicKeys: StringifiedJSONArray;\r\n}\r\n\r\nexport const DefaultAuthUtilityConfig: Readonly<AuthUtilityConfig> = {\r\n maxTokenAge: '30 days',\r\n userPrivateKeys: '[]',\r\n userPublicKeys: '[]',\r\n anonymousPrivateKeys: '[]',\r\n anonymousPublicKeys: '[]',\r\n systemPrivateKeys: '[]',\r\n systemPublicKeys: '[]',\r\n adminPrivateKeys: '[]',\r\n adminPublicKeys: '[]',\r\n};\r\n\r\nexport type AuthTokenType = 'Anon' | 'User' | 'System' | 'Admin' | 'CDN';\r\n\r\nexport interface AuthMiddlewareConfig {\r\n allowAnonymous: boolean;\r\n allowSystem: boolean;\r\n allowUser: boolean;\r\n allowCDN: boolean;\r\n}\r\n\r\nexport const DefaultAuthMiddlewareConfig: Readonly<AuthMiddlewareConfig> = {\r\n allowAnonymous: false,\r\n allowSystem: true,\r\n allowUser: true,\r\n allowCDN: false\r\n};\r\n\r\n/**\r\n * A utility class for JWT authentication and authorization.\r\n */\r\nclass AuthUtility {\r\n private maxTokenAge: string;\r\n private userPrivateKeys: string[];\r\n private userPublicKeys: string[];\r\n private anonymousPrivateKeys: string[];\r\n private anonymousPublicKeys: string[];\r\n private systemPrivateKeys: string[];\r\n private systemPublicKeys: string[];\r\n private adminPrivateKeys: string[];\r\n private adminPublicKeys: string[];\r\n\r\n /**\r\n * Initializes the AuthUtility class with a configuration.\r\n * @param config The configuration for the utility (optional).\r\n */\r\n constructor(config: Partial<AuthUtilityConfig> = DefaultAuthUtilityConfig) {\r\n const {\r\n maxTokenAge,\r\n userPrivateKeys,\r\n userPublicKeys,\r\n anonymousPrivateKeys,\r\n anonymousPublicKeys,\r\n systemPrivateKeys,\r\n systemPublicKeys,\r\n adminPrivateKeys,\r\n adminPublicKeys,\r\n } = { ...DefaultAuthUtilityConfig, ...config };\r\n\r\n this.maxTokenAge = maxTokenAge;\r\n\r\n this.userPrivateKeys = JSON.parse(userPrivateKeys);\r\n this.userPublicKeys = JSON.parse(userPublicKeys);\r\n\r\n this.anonymousPrivateKeys = JSON.parse(anonymousPrivateKeys);\r\n this.anonymousPublicKeys = JSON.parse(anonymousPublicKeys);\r\n\r\n this.systemPrivateKeys = JSON.parse(systemPrivateKeys);\r\n this.systemPublicKeys = JSON.parse(systemPublicKeys);\r\n\r\n this.adminPrivateKeys = JSON.parse(adminPrivateKeys);\r\n this.adminPublicKeys = JSON.parse(adminPublicKeys);\r\n\r\n this.logWarnings();\r\n }\r\n\r\n /**\r\n * Logs warnings if the number of keys exceeds recommended limits.\r\n */\r\n private logWarnings() {\r\n const warn = (type: string, keys: string[], limit: number) =>\r\n keys.length > limit &&\r\n Logger.logWarning(\r\n 'AuthUtility',\r\n `More than ${limit} ${type} keys provided. This is not recommended.`\r\n );\r\n\r\n warn('user private', this.userPrivateKeys, 3);\r\n warn('user public', this.userPublicKeys, 3);\r\n warn('anonymous private', this.anonymousPrivateKeys, 1);\r\n warn('anonymous public', this.anonymousPublicKeys, 3);\r\n warn('system private', this.systemPrivateKeys, 1);\r\n warn('system public', this.systemPublicKeys, 3);\r\n warn('admin private', this.adminPrivateKeys, 1);\r\n warn('admin public', this.adminPublicKeys, 3);\r\n }\r\n\r\n private async createSignedJWT(payload: any, privateKeyString: string, expiration: string){\r\n const privateKey = await importPKCS8(privateKeyString, 'RS256');\r\n const token = await new SignJWT(payload)\r\n .setProtectedHeader({ alg: 'RS256' })\r\n .setExpirationTime(expiration)\r\n .setIssuedAt()\r\n .sign(privateKey);\r\n\r\n return token;\r\n }\r\n\r\n private async verifySignedJWT(token: string, publicKeyString: string[], expiration: string){\r\n for(let i = publicKeyString.length - 1; i > 0 ; i--){\r\n try { \r\n const publicKey = await importSPKI(publicKeyString[i], 'RS256')\r\n const jwt = await jwtVerify(token, publicKey, { clockTolerance: 30, maxTokenAge: expiration });\r\n return jwt.payload;\r\n } catch (error) {\r\n // Try with the next oldest key\r\n continue;\r\n }\r\n }\r\n\r\n const publicKey = await importSPKI(publicKeyString[0], 'RS256')\r\n const jwt = await jwtVerify(token, publicKey, { clockTolerance: 30, maxTokenAge: expiration });\r\n return jwt.payload;\r\n }\r\n\r\n \r\n /**\r\n * Creates an anonymous token with the given ID and additional data.\r\n *\r\n * @param id - The unique identifier for the token. Must be a valid UUID.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no anonymous private keys are found or if the ID is not a valid UUID.\r\n */\r\n async createAnonymousToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.anonymousPrivateKeys.length, ErrorTypes.ANONYMOUS_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n const payload = {\r\n id,\r\n type: 'Anon',\r\n ...additionalData\r\n };\r\n\r\n return await this.createSignedJWT(payload, this.anonymousPrivateKeys[this.anonymousPrivateKeys.length - 1], this.maxTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies an anonymous token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no anonymous public keys are found or if the token type is invalid.\r\n */\r\n async verifyAnonymousToken(token: string){\r\n assert(this.anonymousPublicKeys.length, ErrorTypes.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.anonymousPublicKeys, this.maxTokenAge);\r\n assert(payload.type === 'Anon', ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for a user.\r\n *\r\n * @param id - The UUID of the user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token as a string.\r\n * @throws Will throw an error if no user private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createUserToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.userPrivateKeys.length, ErrorTypes.USER_PRIVATE_KEY_NOT_FOUND);\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n\r\n const payload = {\r\n id,\r\n type: 'User',\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.userPrivateKeys[this.userPrivateKeys.length - 1], this.maxTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided user token by checking its signature and payload.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token if valid.\r\n * @throws Will throw an error if no user public keys are found or if the token type is invalid.\r\n */\r\n async verifyUserToken(token: string){\r\n assert(this.userPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload =await this.verifySignedJWT(token, this.userPublicKeys, this.maxTokenAge);\r\n assert(payload.type === 'User', ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT (JSON Web Token) for a system with the given ID and optional additional data.\r\n *\r\n * @param id - The unique identifier for the system.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no system private keys are found.\r\n */\r\n async createSystemToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.systemPrivateKeys.length, ErrorTypes.SYSTEM_PRIVATE_KEY_NOT_FOUND);\r\n\r\n const payload = {\r\n id,\r\n type: 'System',\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.systemPrivateKeys[this.systemPrivateKeys.length - 1], '5 min');\r\n }\r\n\r\n /**\r\n * Verifies a system token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no system public keys are found or if the token type is not 'System'.\r\n */\r\n async verifySystemToken(token: string){\r\n assert(this.systemPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.systemPublicKeys, '5 min');\r\n assert(payload.type === 'System', ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for an admin user.\r\n *\r\n * @param email - The email of the admin user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token string.\r\n * @throws Will throw an error if no admin private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createAdminToken(email: string, verifier: string, additionalData?: object): Promise<string> {\r\n assert(this.adminPrivateKeys.length, ErrorTypes.ADMIN_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isEmail(email), ErrorTypes.INVALID_EMAIL);\r\n assert(Utils.isURL(verifier), ErrorTypes.INVALID_VERIFIER);\r\n const payload = {\r\n email,\r\n type: 'Admin',\r\n verifier: verifier,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.adminPrivateKeys[this.adminPrivateKeys.length - 1], this.maxTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided admin token by checking its signature and payload.\r\n * Ensures that the token is signed with one of the known admin public keys\r\n * and that the payload type is 'Admin'.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @param permissions - The permissions required for the admin user.\r\n * @param authenticate - Whether to authenticate the token with the verifier.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no admin public keys are found or if the token is invalid or if the admin doesn't have proper permissions.\r\n */\r\n async verifyAdminToken(token: string, permissions: string[], authenticate: boolean){\r\n assert(this.adminPublicKeys.length, ErrorTypes.ADMIN_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.adminPublicKeys, this.maxTokenAge);\r\n assert(payload.type === 'Admin', ErrorTypes.INVALID_AUTH_TYPE);\r\n\r\n if(authenticate) {\r\n const response = await Fetch(payload.verifier as string, '', 'POST', {}, { token, permissions });\r\n assert(response.data.isTokenValid === true, ErrorTypes.INVALID_TOKEN);\r\n \r\n if(response.data.hasPermissions !== true){\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_PERMISSIONS)\r\n }\r\n }\r\n\r\n return payload;\r\n }\r\n\r\n /**\r\n * Middleware function to handle authentication based on different token types.\r\n * It verifies the token and sets the authentication details in the response locals.\r\n *\r\n * @param {Partial<AuthMiddlewareConfig>} [config=DefaultAuthMiddlewareConfig] - Configuration object to customize the middleware behavior.\r\n * @returns Middleware function to handle authentication.\r\n */\r\n AuthMiddleware(config: Partial<AuthMiddlewareConfig> = DefaultAuthMiddlewareConfig, permissions: string[] = []) {\r\n const { allowAnonymous, allowSystem, allowUser, allowCDN } = { ...DefaultAuthMiddlewareConfig, ...config };\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n if (!token) throw new Error(ErrorTypes.INVALID_TOKEN);\r\n\r\n let payload;\r\n switch (authType as AuthTokenType) {\r\n case 'Anon':\r\n if (!allowAnonymous) throw ResponseUtility.generateError(403, ErrorTypes.ANONYMOUS_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyAnonymousToken(token);\r\n break;\r\n case 'User':\r\n if (!allowUser) throw ResponseUtility.generateError(403, ErrorTypes.USER_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyUserToken(token);\r\n break;\r\n case 'System':\r\n if (!allowSystem) throw ResponseUtility.generateError(403, ErrorTypes.SYSTEM_SESSION_NOT_ALLOWED);\r\n payload = await this.verifySystemToken(token);\r\n Logger.logMessage('AuthMiddleware', `System Name - ${payload.id}`);\r\n break;\r\n case 'Admin':\r\n payload = await this.verifyAdminToken(token, permissions, true);\r\n Logger.logMessage('AuthMiddleware', `Admin - ${payload.email}`);\r\n break;\r\n case 'CDN':\r\n if (!allowCDN) throw ResponseUtility.generateError(403, ErrorTypes.CDN_SESSION_NOT_ALLOWED);\r\n assert(['E3CQMOP5FX6KD1', 'E3TNCKKZ3FOX9W'].includes(token), ErrorTypes.INVALID_TOKEN);\r\n Logger.logMessage('AuthMiddleware', `CDN DistributionId - ${token}`);\r\n break;\r\n default:\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_AUTH_TYPE);\r\n }\r\n\r\n res.locals.auth = { authType, token, ...payload };\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthMiddleware',\r\n ResponseUtility.generateError(401, error.error || ErrorTypes.TOKEN_EXPIRED, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n}\r\n\r\nexport default AuthUtility;\r\n\r\n"]}
@@ -0,0 +1,142 @@
1
+ import BaseModel, { BaseAttributes } from './Base.mjs';
2
+ import './Common.mjs';
3
+ import './Enum.mjs';
4
+
5
+ declare enum AddressType {
6
+ BILLING = "billing",
7
+ SHIPPING = "shipping",
8
+ BILLING_AND_SHIPPING = "billing&shipping",
9
+ NONE = "none"
10
+ }
11
+ type AddressAttributes = BaseAttributes & {
12
+ id: string;
13
+ firstName: string;
14
+ lastName: string;
15
+ phone: string;
16
+ email: string;
17
+ addressLine1: string;
18
+ addressLine2?: string;
19
+ city: string;
20
+ postalCode: string;
21
+ state: string;
22
+ country: string;
23
+ isBillingAddress: boolean;
24
+ isShippingAddress: boolean;
25
+ };
26
+ type AddressData = Required<AddressAttributes>;
27
+ /**
28
+ * Represents a physical address associated with a customer or order.
29
+ * Handles both billing and shipping address types.
30
+ */
31
+ declare class AddressModel extends BaseModel {
32
+ protected id: string;
33
+ protected firstName: string;
34
+ protected lastName: string;
35
+ protected phone: string;
36
+ protected email: string;
37
+ protected addressLine1: string;
38
+ protected addressLine2: string;
39
+ protected city: string;
40
+ protected postalCode: string;
41
+ protected state: string;
42
+ protected country: string;
43
+ protected isBillingAddress: boolean;
44
+ protected isShippingAddress: boolean;
45
+ /**
46
+ * Creates an instance of AddressModel.
47
+ * @param data - The initial address attributes.
48
+ * @param date - Optional date for setting creation/modification times (defaults to now).
49
+ */
50
+ constructor(data: AddressAttributes, date?: Date);
51
+ /**
52
+ * Gets a plain data object representing the address's current state.
53
+ * Includes all address fields and base model fields.
54
+ * @returns AddressData object suitable for serialization or API responses.
55
+ */
56
+ getDetails(): AddressData;
57
+ /**
58
+ * Gets the unique identifier for the address.
59
+ * @returns The address ID.
60
+ */
61
+ getId(): string;
62
+ /**
63
+ * Gets the first name associated with the address.
64
+ * @returns The first name.
65
+ */
66
+ getFirstName(): string;
67
+ /**
68
+ * Gets the last name associated with the address.
69
+ * @returns The last name.
70
+ */
71
+ getLastName(): string;
72
+ /**
73
+ * Gets the phone number associated with the address.
74
+ * @returns The phone number.
75
+ */
76
+ getPhone(): string;
77
+ /**
78
+ * Gets the email address associated with the address.
79
+ * @returns The email address.
80
+ */
81
+ getEmail(): string;
82
+ /**
83
+ * Gets the primary address line (e.g., street address).
84
+ * @returns The first address line.
85
+ */
86
+ getAddressLine1(): string;
87
+ /**
88
+ * Gets the secondary address line (e.g., apartment, suite).
89
+ * Returns an empty string if not provided.
90
+ * @returns The second address line or an empty string.
91
+ */
92
+ getAddressLine2(): string;
93
+ /**
94
+ * Gets the city name.
95
+ * @returns The city.
96
+ */
97
+ getCity(): string;
98
+ /**
99
+ * Gets the postal code (e.g., ZIP code).
100
+ * @returns The postal code.
101
+ */
102
+ getPostalCode(): string;
103
+ /**
104
+ * Gets the state, province, or region.
105
+ * @returns The state.
106
+ */
107
+ getState(): string;
108
+ /**
109
+ * Gets the country name or code.
110
+ * @returns The country.
111
+ */
112
+ getCountry(): string;
113
+ /**
114
+ * Checks if this address is designated as a billing address.
115
+ * @returns True if it's a billing address, false otherwise.
116
+ */
117
+ getIsBillingAddress(): boolean;
118
+ /**
119
+ * Checks if this address is designated as a shipping address.
120
+ * @returns True if it's a shipping address, false otherwise.
121
+ */
122
+ getIsShippingAddress(): boolean;
123
+ /**
124
+ * Determines the type of the address based on its billing and shipping flags.
125
+ * @returns The AddressType enum value representing the address's role.
126
+ */
127
+ getAddressType(): AddressType;
128
+ /**
129
+ * Static method to check if a given AddressType includes shipping.
130
+ * @param addressType - The address type to check.
131
+ * @returns True if the type is SHIPPING or BILLING_AND_SHIPPING.
132
+ */
133
+ static checkIfShippingAddress(addressType: AddressType): boolean;
134
+ /**
135
+ * Static method to check if a given AddressType includes billing.
136
+ * @param addressType - The address type to check.
137
+ * @returns True if the type is BILLING or BILLING_AND_SHIPPING.
138
+ */
139
+ static checkIfBillingAddress(addressType: AddressType): boolean;
140
+ }
141
+
142
+ export { type AddressAttributes, type AddressData, AddressType, AddressModel as default };