-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcat.ts
More file actions
297 lines (272 loc) · 7.51 KB
/
cat.ts
File metadata and controls
297 lines (272 loc) · 7.51 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
import * as cbor from 'cbor-x';
import cose from 'cose-js';
import {
InvalidAudienceError,
InvalidClaimTypeError,
InvalidIssuerError,
TokenExpiredError,
TokenNotActiveError
} from './errors';
import { CatValidationOptions } from '.';
const claimsToLabels: { [key: string]: number } = {
iss: 1, // 3
sub: 2, // 3
aud: 3, // 3
exp: 4, // 6 tag value 1
nbf: 5, // 6 tag value 1
iat: 6, // 6 tag value 1
cti: 7, // 2,
cnf: 8,
catreplay: 308,
catpor: 309,
catv: 310,
catnip: 311,
catu: 312,
catm: 313,
catalpn: 314,
cath: 315,
catgeoiso3166: 316,
catgeocoord: 317,
cattpk: 319,
catifdata: 320,
catadpop: 321,
catif: 322,
catr: 323
};
const labelsToClaim: { [key: number]: string } = {
1: 'iss',
2: 'sub',
3: 'aud',
4: 'exp',
5: 'nbf',
6: 'iat',
7: 'cti',
8: 'cnf',
308: 'catreplay',
309: 'catpor',
310: 'catv',
311: 'catnip',
312: 'catu',
313: 'catm',
314: 'catalpn',
315: 'cath',
316: 'catgeoiso3166',
317: 'catgeocoord',
319: 'cattpk',
320: 'catifdata',
321: 'catadpop',
322: 'catif',
323: 'catr'
};
const claimTransform: { [key: string]: (value: string) => Buffer } = {
cti: (value) => Buffer.from(value, 'hex'),
cattpk: (value) => Buffer.from(value, 'hex')
};
const claimTransformReverse: { [key: string]: (value: Buffer) => string } = {
cti: (value: Buffer) => value.toString('hex'),
cattpk: (value: Buffer) => value.toString('hex')
};
const claimTypeValidators: { [key: string]: (value: string) => boolean } = {
iss: (value) => typeof value === 'string',
exp: (value) => typeof value === 'number',
aud: (value) => typeof value === 'string' || Array.isArray(value),
nbf: (value) => typeof value === 'number'
};
const CWT_TAG = 61;
export type CommonAccessTokenClaims = { [key: string]: string | number };
export type CommonAccessTokenValue = string | number | Buffer;
export interface CWTEncryptionKey {
k: Buffer;
kid: string;
}
export interface CWTDecryptionKey {
k: Buffer;
kid: string;
}
export interface CWTSigningKey {
d: Buffer;
kid: string;
}
export interface CWTVerifierKey {
x: Buffer;
y: Buffer;
kid: string;
}
function updateMapFromClaims(
claims: CommonAccessTokenClaims
): Map<number, CommonAccessTokenValue> {
const map = new Map<number, CommonAccessTokenValue>();
let dict = claims;
if (claims instanceof Map) {
dict = Object.fromEntries(claims);
}
for (const param in dict) {
const key = claimsToLabels[param] ? claimsToLabels[param] : parseInt(param);
const value = claimTransform[param]
? claimTransform[param](dict[param] as string)
: dict[param];
map.set(key, value);
}
return map;
}
export class CommonAccessToken {
private payload: Map<number, CommonAccessTokenValue>;
private data?: Buffer;
constructor(claims: CommonAccessTokenClaims) {
this.payload = updateMapFromClaims(claims);
}
public async mac(
key: CWTEncryptionKey,
alg: string,
opts?: {
addCwtTag: boolean;
}
): Promise<void> {
const headers = {
p: { alg: alg },
u: { kid: key.kid }
};
const recipient = {
key: key.k
};
if (opts?.addCwtTag) {
const plaintext = cbor.encode(this.payload);
const coseMessage = await cose.mac.create(
headers,
plaintext as unknown as string,
recipient
);
const decoded = cbor.decode(coseMessage).value;
const coseTag = new cbor.Tag(decoded, 17);
const cwtTag = new cbor.Tag(coseTag, CWT_TAG);
this.data = cbor.encode(cwtTag);
} else {
const plaintext = cbor.encode(this.payload).toString('hex');
this.data = await cose.mac.create(headers, plaintext, recipient);
}
}
public async parse(
token: Buffer,
key: CWTDecryptionKey,
opts?: {
expectCwtTag: boolean;
}
): Promise<void> {
const coseMessage = cbor.decode(token);
if (opts?.expectCwtTag && coseMessage.tag !== 61) {
throw new Error('Expected CWT tag');
}
if (coseMessage.tag === CWT_TAG) {
const cborCoseMessage = cbor.encode(coseMessage.value);
const buf = await cose.mac.read(cborCoseMessage, key.k);
const json = await cbor.decode(buf);
this.payload = updateMapFromClaims(json);
} else {
const buf = await cose.mac.read(token, key.k);
this.payload = await cbor.decode(Buffer.from(buf.toString('hex'), 'hex'));
}
}
public async sign(key: CWTSigningKey, alg: string): Promise<void> {
const plaintext = cbor.encode(this.payload).toString('hex');
const headers = {
p: { alg: alg },
u: { kid: key.kid }
};
const signer = {
key: key
};
this.data = await cose.sign.create(headers, plaintext, signer);
}
public async verify(
token: Buffer,
key: CWTVerifierKey
): Promise<CommonAccessToken> {
const buf = await cose.sign.verify(token, { key: key });
this.payload = await cbor.decode(Buffer.from(buf.toString('hex'), 'hex'));
return this;
}
private async validateTypes() {
for (const [key, value] of this.payload) {
const claim = labelsToClaim[key];
if (value && claimTypeValidators[claim]) {
if (!claimTypeValidators[claim](value as string)) {
throw new InvalidClaimTypeError(claim, value as string);
}
}
}
}
public async isValid(opts: CatValidationOptions): Promise<boolean> {
this.validateTypes();
if (
this.payload.get(claimsToLabels['iss']) &&
this.payload.get(claimsToLabels['iss']) !== opts.issuer
) {
throw new InvalidIssuerError(this.payload.get(claimsToLabels['iss']));
}
if (
this.payload.get(claimsToLabels['exp']) &&
(this.payload.get(claimsToLabels['exp']) as number) < Date.now() / 1000
) {
throw new TokenExpiredError();
}
if (opts.audience) {
const value = this.payload.get(claimsToLabels['aud']);
if (value) {
const claimAud = Array.isArray(value) ? value : [value];
if (!opts.audience.some((item) => claimAud.includes(item))) {
throw new InvalidAudienceError(claimAud as string[]);
}
}
}
if (
this.payload.get(claimsToLabels['nbf']) &&
(this.payload.get(claimsToLabels['nbf']) as number) >
Math.floor(Date.now() / 1000)
) {
throw new TokenNotActiveError();
}
return true;
}
get(key: string) {
const theKey = claimsToLabels[key] ? claimsToLabels[key] : parseInt(key);
return this.payload.get(theKey);
}
get claims() {
const result: { [key: string]: string | number } = {};
this.payload.forEach((value, param) => {
const key = labelsToClaim[param] ? labelsToClaim[param] : param;
const theValue = claimTransformReverse[key]
? claimTransformReverse[key](value as Buffer)
: (value as string | number);
result[key] = theValue;
});
return result;
}
get raw() {
return this.data;
}
get base64() {
return this.data?.toString('base64');
}
}
export class CommonAccessTokenFactory {
public static async fromSignedToken(
base64encoded: string,
key: CWTVerifierKey
): Promise<CommonAccessToken> {
const token = Buffer.from(base64encoded, 'base64');
const cat = new CommonAccessToken({});
await cat.verify(token, key);
return cat;
}
public static async fromMacedToken(
base64encoded: string,
key: CWTDecryptionKey,
expectCwtTag: boolean
): Promise<CommonAccessToken> {
const token = Buffer.from(base64encoded, 'base64');
const cat = new CommonAccessToken({});
await cat.parse(token, key, { expectCwtTag });
return cat;
}
}