-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathToken.ts
More file actions
298 lines (251 loc) · 10.5 KB
/
Token.ts
File metadata and controls
298 lines (251 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import {TokenVersion} from "./model/TokenVersion";
import {EnqueueTokenPayload, IEnqueueTokenPayload} from "./Payload";
import {EncryptionType} from "./model/EncryptionType";
import {ShaHashing, Utils} from "./QueueITHelpers";
import {HeaderDto} from "./model/HeaderDto";
import {Base64} from "./helpers/Base64";
const InvalidTokenExceptionMessage = "Invalid token";
export class Token {
public static Enqueue(customerId: string, tokenIdentifierPrefix?: string): EnqueueTokenGenerator {
return new EnqueueTokenGenerator(customerId, tokenIdentifierPrefix);
}
public static Parse(token: string, secretKey: string): IEnqueueToken {
return EnqueueToken.Parse(token, secretKey);
}
}
export class EnqueueTokenGenerator {
private _token: EnqueueToken;
constructor(customerId: string, tokenIdentifier?: string) {
this._token = new EnqueueToken(customerId, tokenIdentifier);
}
public WithEventId(eventId: string): EnqueueTokenGenerator {
this._token = EnqueueToken.AddEventId(this._token, eventId);
return this;
}
public WithValidity(validityMillis: number): EnqueueTokenGenerator {
const newExpiryTime = this._token.Issued.getTime() + validityMillis;
this._token = EnqueueToken.AddExpires(this._token, newExpiryTime);
return this;
}
public WithValidityDate(validity: Date): EnqueueTokenGenerator {
this._token = EnqueueToken.AddExpiresWithDate(this._token, validity);
return this
}
public WithPayload(payload: IEnqueueTokenPayload): EnqueueTokenGenerator {
this._token = EnqueueToken.AddPayload(this._token, payload);
return this;
}
public WithIpAddress(ip: string, xForwardedFor: string): EnqueueTokenGenerator {
this._token = EnqueueToken.AddIPAddress(this._token, ip, xForwardedFor);
return this;
}
public Generate(secretKey: string): IEnqueueToken {
this._token.Generate(secretKey);
return this._token;
}
}
export class EnqueueToken {
private readonly _tokenIdentifierPrefix: string;
public CustomerId: string
public EventId: string
public IpAddress: string
public XForwardedFor: string
public Issued: Date
public readonly TokenVersion: TokenVersion = TokenVersion.QT1;
public readonly Encryption: EncryptionType = EncryptionType.AES256;
public Expires: Date
private _tokenIdentifier: string
private _payload: IEnqueueTokenPayload
private _tokenWithoutHash: string
private _hashCode: string
public get Payload(): IEnqueueTokenPayload {
return this._payload;
}
private set Payload(value: IEnqueueTokenPayload) {
this._payload = value;
}
public get Token(): string {
return this.TokenWithoutHash + "." + this.HashCode
};
get HashCode(): string {
return this._hashCode;
}
private set HashCode(value: string) {
this._hashCode = value;
}
get TokenWithoutHash(): string {
return this._tokenWithoutHash;
}
private set TokenWithoutHash(value: string) {
this._tokenWithoutHash = value;
}
get TokenIdentifier(): string {
return this._tokenIdentifier
}
private set TokenIdentifier(value: string) {
this._tokenIdentifier = value;
}
constructor(customerId: string, tokenIdentifierPrefix: string) {
this._tokenIdentifierPrefix = tokenIdentifierPrefix;
this.CustomerId = customerId;
this.Issued = new Date(Utils.utcNow());
this.Expires = Utils.maxDate();
this._tokenIdentifier = EnqueueToken.GetTokenIdentifier(tokenIdentifierPrefix);
}
public static Create(tokenIdentifier: string,
customerId: string,
eventId: string,
issued: Date,
expires: Date,
ipAddress: string,
xForwardedFor: string,
payload: IEnqueueTokenPayload) {
const token = new EnqueueToken(customerId, "");
token.TokenIdentifier = tokenIdentifier;
token.CustomerId = customerId;
token.EventId = eventId;
token.Issued = issued;
token.Expires = expires ?? Utils.maxDate();
token.Payload = payload;
token.IpAddress = ipAddress;
token.XForwardedFor = xForwardedFor;
return token;
}
private static GetTokenIdentifier(tokenIdentifierPrefix: string): string {
return tokenIdentifierPrefix && tokenIdentifierPrefix.length > 0
? `${tokenIdentifierPrefix}~${Utils.generateUUID()}`
: Utils.generateUUID();
}
public Generate(secretKey: string, resetTokenIdentifier: boolean = true) {
if (resetTokenIdentifier) {
this.TokenIdentifier = EnqueueToken.GetTokenIdentifier(this._tokenIdentifierPrefix)
}
try {
const utcTimeIssued = this.Issued.getTime();
const utcTimeExpires = (this.Expires && this.Expires.getTime() == Utils.maxDate().getTime()) ? null :
this.Expires.getTime();
const dto = new HeaderDto();
dto.CustomerId = this.CustomerId;
dto.EventId = this.EventId;
dto.TokenIdentifier = this.TokenIdentifier;
dto.Issued = utcTimeIssued;
dto.Expires = utcTimeExpires;
dto.Encryption = EncryptionType[EncryptionType.AES256];
dto.TokenVersion = TokenVersion[TokenVersion.QT1];
dto.IpAddress = this.IpAddress;
dto.XForwardedFor = this.XForwardedFor;
let serialized = dto.Serialize() + ".";
if (this.Payload) {
serialized += this.Payload.EncryptAndEncode(secretKey, this.TokenIdentifier);
}
this.TokenWithoutHash = serialized;
const sha256Hash = ShaHashing.GenerateHash(secretKey, this.TokenWithoutHash);
this.HashCode = Base64.encode(sha256Hash);
} catch (ex) {
throw new TokenSerializationException(ex);
}
}
public static Parse(tokenString: string, secretKey: string): IEnqueueToken {
if (!secretKey || secretKey.length == 0) {
throw new ArgumentException("Invalid secret key");
}
if (!tokenString || tokenString.length == 0) {
throw new ArgumentException(InvalidTokenExceptionMessage);
}
const tokenParts = tokenString.split(".");
const headerPart = tokenParts[0];
const payloadPart = tokenParts[1];
const hashPart = tokenParts[2];
if (headerPart.length == 0) {
throw new ArgumentException(InvalidTokenExceptionMessage);
}
if (hashPart.length == 0) {
throw new ArgumentException(InvalidTokenExceptionMessage);
}
const token = headerPart + "." + payloadPart;
const hash = ShaHashing.GenerateHash(secretKey, token);
const expectedHash = Base64.encode(hash);
if (expectedHash != hashPart) {
throw new InvalidHashException();
}
try {
const headerModel = HeaderDto.DeserializeHeader(headerPart);
let payload: EnqueueTokenPayload;
if (payloadPart.length > 0) {
payload = EnqueueTokenPayload.Deserialize(payloadPart, secretKey, headerModel.TokenIdentifier);
}
const issuedTime: Date = new Date(headerModel.Issued);
const expiresDate: Date = headerModel.Expires
? (new Date(headerModel.Expires))
: null;
const enqueueToken = EnqueueToken.Create(
headerModel.TokenIdentifier,
headerModel.CustomerId,
headerModel.EventId,
issuedTime,
expiresDate,
headerModel.IpAddress,
headerModel.XForwardedFor,
payload);
enqueueToken.TokenWithoutHash = token;
enqueueToken.HashCode = expectedHash;
return enqueueToken;
} catch (ex) {
throw new TokenDeserializationException("Unable to deserialize token", ex);
}
}
static AddIPAddress(token: EnqueueToken, ipAddress: string, xForwardedFor: string): EnqueueToken {
return EnqueueToken.Create(token.TokenIdentifier, token.CustomerId, token.EventId, token.Issued, token.Expires, ipAddress, xForwardedFor, token.Payload);
}
static AddEventId(token: EnqueueToken, eventId: string): EnqueueToken {
return EnqueueToken.Create(token.TokenIdentifier, token.CustomerId, eventId, token.Issued, token.Expires, token.IpAddress, token.XForwardedFor, token.Payload);
}
static AddExpires(token: EnqueueToken, expires: number): EnqueueToken {
return EnqueueToken.Create(token.TokenIdentifier, token.CustomerId, token.EventId, token.Issued, new Date(expires), token.IpAddress, token.XForwardedFor, token.Payload);
}
static AddExpiresWithDate(token: EnqueueToken, expires: Date): EnqueueToken {
return EnqueueToken.Create(token.TokenIdentifier, token.CustomerId, token.EventId, token.Issued, expires, token.IpAddress, token.XForwardedFor, token.Payload);
}
static AddPayload(token: EnqueueToken, payload: IEnqueueTokenPayload): EnqueueToken {
return EnqueueToken.Create(token.TokenIdentifier, token.CustomerId, token.EventId, token.Issued, token.Expires, token.IpAddress, token.XForwardedFor, payload);
}
}
export class TokenDeserializationException extends Error {
public readonly InternalException: Error
public constructor(message: string, ex: Error) {
super(message);
this.InternalException = ex;
}
}
export class InvalidHashException extends TokenDeserializationException {
public constructor() {
super("The token hash is invalid", null);
}
}
export class TokenSerializationException extends Error {
public readonly InternalException: Error
public constructor(ex: Error) {
super("Exception serializing token");
this.InternalException = ex;
}
}
export class ArgumentException extends Error {
constructor(message: string) {
super(message);
}
}
export interface IEnqueueToken {
readonly TokenVersion: TokenVersion
readonly Encryption: EncryptionType
readonly Issued: Date
readonly Expires: Date
readonly TokenIdentifier: string
readonly CustomerId: string
readonly EventId: string
readonly IpAddress: string
readonly XForwardedFor: string
readonly Payload: IEnqueueTokenPayload
readonly TokenWithoutHash: string
readonly Token: string
readonly HashCode: string
}