-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.ts
524 lines (431 loc) · 13.4 KB
/
mod.ts
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import {
Curve25519,
encode,
decode,
hchacha20,
HCHACHA20_OUTPUT_BYTES,
HCHACHA20_NONCE_BYTES,
seal,
open,
XCHACHA20_POLY1305_NONCE_BYTES,
XCHACHA20_POLY1305_AAD_BYTES_MAX,
XCHACHA20_POLY1305_PLAINTEXT_BYTES_MAX,
XCHACHA20_CIPHERTEXT_BYTES_MAX,
} from "./deps.ts";
/** Supported BWT versions. */
export const SUPPORTED_VERSIONS: Set<number> = new Set<number>([0]);
/** Maximum allowed number of characters of a token. */
export const MAX_TOKEN_CHARS: number = 4096;
/** Byte length of a Curve25519 secret key. */
export const SECRET_KEY_BYTES: number = 32;
/** Byte length of a Curve25519 public key. */
export const PUBLIC_KEY_BYTES: number = 32;
/** Byte length of a BWT kid. */
export const KID_BYTES: number = 16;
/** Byte length of a serialized header. */
const HEADER_BYTES: number = 60;
/** Global Curve25519 instance provding a scalar multiplication op. */
const CURVE25519: Curve25519 = new Curve25519();
/** BigInt byte mask. */
const BIGINT_BYTE_MASK: bigint = 255n;
/** BigInt 8. */
const BIGINT_BYTE_SHIFT: bigint = 8n;
/** "BWT" as buffer - magic bytes. */
const BWT_MAGIC: Uint8Array = Uint8Array.from([66, 87, 84]);
/** HChacha20 all-zero nonce used for key stretching. */
const HCHACHA20_ZERO_NONCE: Uint8Array = new Uint8Array(HCHACHA20_NONCE_BYTES);
/** BWT context constant used with HChaCha20 for key stretching. */
const BWT_CONTEXT: Uint8Array = encode("BETTER_WEB_TOKEN", "utf8");
/** BWT format regex. */
const BWT_PATTERN: RegExp =
/^QldU[A-Za-z0-9-_]{76}\.[A-Za-z0-9-_]{3,3992}\.[A-Za-z0-9-_]{22}$/;
/** Curve25519 low-order public keys. https://cr.yp.to/ecdh.html#validate */
const LOW_ORDER_PUBLIC_KEYS: Uint8Array[] = [
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"4Ot6fDtBuK4WVuP68Z_EatoJjeucMrH9hmIFFl9JuAA=",
"X5yVvKNQjCSx0LFVnIPvWwREXMRYHI6G2CJO3dCfEVc=",
"7P_______________________________________38=",
"7f_______________________________________38=",
"7v_______________________________________38=",
"zet6fDtBuK4WVuP68Z_EatoJjeucMrH9hmIFFl9JuIA=",
"TJyVvKNQjCSx0LFVnIPvWwREXMRYHI6G2CJO3dCfEdc=",
"2f________________________________________8=",
"2v________________________________________8=",
"2_________________________________________8=",
].map((publicKey: string): Uint8Array => encode(publicKey, "base64url"));
/** Typ enum indicating a BWT version @ the Header.typ field. */
export const enum Typ {
BWTv0,
}
/**
* BWT header object.
*
* typ must be a supported BWT version, currently that is Typ.BWTv0 only.
* iat and exp denote the issued-at and expiry ms timestamps of a token.
* kid is the public key identifier of the issuing party.
*/
export interface Header {
typ: Typ;
iat: number;
exp: number;
kid: Uint8Array;
}
/** BWT body object. */
export interface Body {
[key: string]: unknown;
}
/** Parsed contents of a token. */
export interface Contents {
header: Header;
body: Body;
}
/** BWT stringify function. */
export interface Stringify {
(header: Header, body: Body): null | string;
}
/** BWT parse function. */
export interface Parse {
(token: string): null | Contents;
}
/**
* BWT keypair object including a key identifier for the public key.
*
* secretKey is the 32-byte secret key.
* publicKey is the 32-byte public key.
* kid is a 16-byte key identifier for the public key.
*/
export interface KeyPair {
secretKey: Uint8Array;
publicKey: Uint8Array;
kid: Uint8Array;
}
/**
* BWT public key of a peer.
*
* publicKey is the 32-byte public key.
* kid is a 16-byte key identifer for the public key.
* name can be an arbitrarily encoded string.
*/
export interface PeerPublicKey {
publicKey: Uint8Array;
kid: Uint8Array;
name?: string;
}
/** Return values of the xchacha20-poly1305 seal op. */
interface Sealed {
aad: Uint8Array;
ciphertext: Uint8Array;
tag: Uint8Array;
}
/** Branchless buffer equality check. */
function constantTimeEqual(
actual: Uint8Array,
expected: Uint8Array,
length: number,
): boolean {
let diff: number = 0;
for (let i: number = 0; i < length; ++i) {
diff |= actual[i] ^ expected[i];
}
return diff === 0;
}
/** Whether given public key has a low order? */
function isLowOrderPublicKey(publicKey: Uint8Array): boolean {
return LOW_ORDER_PUBLIC_KEYS.some((lowOrderPublicKey: Uint8Array): boolean =>
constantTimeEqual(publicKey, lowOrderPublicKey, PUBLIC_KEY_BYTES)
);
}
/** Reads given bytes as an unsigned big-endian bigint. */
function bytesToBigIntBE(buf: Uint8Array): bigint {
return buf.reduce(
(acc: bigint, byte: number): bigint =>
(acc << BIGINT_BYTE_SHIFT) | (BigInt(byte) & BIGINT_BYTE_MASK),
0n,
);
}
/** Writes given timestamp to big-endian bytes of an 8-byte out buffer. */
function bigintToBytesBE(b: bigint, out: Uint8Array): void {
for (let i: number = out.byteLength - 1; i >= 0; --i) {
out[i] = Number(b & BIGINT_BYTE_MASK);
b >>= BIGINT_BYTE_SHIFT;
}
}
/** Converts a header and nonce to a 60-byte buffer. */
function headerAndNonceToBuffer(
header: Header,
nonce: Uint8Array,
): Uint8Array {
const buf: Uint8Array = new Uint8Array(HEADER_BYTES);
buf.set(BWT_MAGIC, 0);
buf[3] = header.typ;
bigintToBytesBE(BigInt(header.iat), buf.subarray(4, 12));
bigintToBytesBE(BigInt(header.exp), buf.subarray(12, 20));
buf.set(header.kid, 20);
buf.set(nonce, 36);
return buf;
}
/** Converts a buffer to metadata of the form: [header, kid, nonce]. */
function bufferToMetadata(buf: Uint8Array): [Header, string, Uint8Array] {
return [
{
typ: buf[3],
iat: Number(bytesToBigIntBE(buf.subarray(4, 12))),
exp: Number(bytesToBigIntBE(buf.subarray(12, 20))),
kid: buf.subarray(20, 36),
},
decode(buf.subarray(20, 36), "base64url"),
buf.subarray(36, HEADER_BYTES),
];
}
/** Shared key derivation. */
function deriveSharedKey(
secretKey: Uint8Array,
publicKey: Uint8Array,
): Uint8Array {
const sharedSecret: Uint8Array = CURVE25519.scalarMult(secretKey, publicKey);
const sharedKey: Uint8Array = new Uint8Array(HCHACHA20_OUTPUT_BYTES);
hchacha20(sharedKey, sharedSecret, HCHACHA20_ZERO_NONCE, BWT_CONTEXT);
sharedSecret.fill(0x00);
return sharedKey;
}
/** Transforms a collection of peer public keys to a shared key map. */
function toSharedKeyMap(
ownSecretKey: Uint8Array,
peerPublicKeys: PeerPublicKey[],
): Map<string, Uint8Array> {
return new Map<string, Uint8Array>(
peerPublicKeys.map((peerPublicKey: PeerPublicKey): [string, Uint8Array] => [
decode(peerPublicKey.kid, "base64url"),
deriveSharedKey(ownSecretKey, peerPublicKey.publicKey),
]),
);
}
/** Concatenates aad, ciphertext, and tag to a token. */
function assembleToken(
aad: Uint8Array,
ciphertext: Uint8Array,
tag: Uint8Array,
): string {
return (
decode(aad, "base64url") +
"." +
decode(ciphertext, "base64url") +
"." +
decode(tag, "base64url")
);
}
/** Whether given input is a valid BWT header object. */
function isValidHeader(x: any): boolean {
const now: number = Date.now();
return (
x &&
SUPPORTED_VERSIONS.has(x.typ) &&
x.kid &&
x.kid.byteLength === KID_BYTES &&
x.iat >= 0 &&
x.iat % 1 === 0 &&
x.iat <= now &&
x.exp >= 0 &&
x.exp % 1 === 0 &&
x.exp > now
);
}
/** Whether given input is a valid BWT secret key. */
function isValidSecretKey(x: Uint8Array): boolean {
return x && x.byteLength === SECRET_KEY_BYTES;
}
/** Whether given input is a valid BWT peer public key. */
function isValidPeerPublicKey(x: PeerPublicKey): boolean {
return (
x &&
x.kid &&
x.kid.byteLength === KID_BYTES &&
x.publicKey &&
x.publicKey.byteLength === PUBLIC_KEY_BYTES &&
!isLowOrderPublicKey(x.publicKey)
);
}
/** Whether given input string has a valid token size. */
function hasValidTokenSize(x: string): boolean {
return x.length <= MAX_TOKEN_CHARS;
}
/** Naive BWT format validation. */
function hasValidTokenFormat(x: string): boolean {
return BWT_PATTERN.test(x);
}
/** Generates a BWT key pair. */
export function generateKeyPair(): KeyPair {
const seed: Uint8Array = new Uint8Array(SECRET_KEY_BYTES);
const kid: Uint8Array = new Uint8Array(KID_BYTES);
crypto.getRandomValues(seed);
// keypair is null only if seed.length != 32 :: SECRET_KEY_BYTES === 32
const keypair: {
secretKey: Uint8Array;
publicKey: Uint8Array;
} = CURVE25519.generateKeys(seed) as {
secretKey: Uint8Array;
publicKey: Uint8Array;
};
seed.fill(0x00);
if (isLowOrderPublicKey(keypair.publicKey)) {
keypair.secretKey.fill(0x00);
return generateKeyPair();
}
crypto.getRandomValues(kid);
return { ...keypair, kid };
}
/**
* Creates a BWT stringify function.
*
* ownSecretKey must be a buffer of 32 bytes.
* peerPublicKey must be a peer public key object.
*
* Throws TypeErrors if any of its arguments are invalid.
*/
export function createStringify(
ownSecretKey: Uint8Array,
peerPublicKey: PeerPublicKey,
): Stringify {
if (!isValidSecretKey(ownSecretKey)) {
throw new TypeError("invalid secret key");
}
if (!isValidPeerPublicKey(peerPublicKey)) {
throw new TypeError("invalid peer public key");
}
const sharedKey: Uint8Array = deriveSharedKey(
ownSecretKey,
peerPublicKey.publicKey,
);
/**
* Stringifies header and body to an authenticated and encrypted token.
*
* header must be a BWT header object.
* body must be a serializable object with string keys.
*
* Returns null in case of invalid inputs, if the body is too big
* (token.length > 4096), or other exceptions, fx JSON.stringify(body) -> 💥
*/
return function stringify(header: Header, body: Body): null | string {
if (!isValidHeader(header) || !body) {
return null;
}
let token: string;
try {
const nonce: Uint8Array = crypto.getRandomValues(
new Uint8Array(XCHACHA20_POLY1305_NONCE_BYTES),
);
const aad: Uint8Array = headerAndNonceToBuffer(header, nonce);
if (aad.byteLength > XCHACHA20_POLY1305_AAD_BYTES_MAX) {
return null;
}
const plaintext: Uint8Array = encode(JSON.stringify(body), "utf8");
if (plaintext.byteLength > XCHACHA20_POLY1305_PLAINTEXT_BYTES_MAX) {
return null;
}
// NOTE: all args to seal r of correct length - will return Sealed
const sealed: Sealed = seal(sharedKey, nonce, plaintext, aad) as Sealed;
plaintext.fill(0x00);
token = assembleToken(sealed.aad, sealed.ciphertext, sealed.tag);
} catch (_) {
return null;
}
if (!hasValidTokenSize(token)) {
return null;
}
return token;
};
}
/**
* Creates a BWT parse function.
*
* ownSecretKey must be a buffer of 32 bytes.
* peerPublicKeys must be a non-empty peer public key collection to be used for
* verification of incoming tokens.
*
* Throws TypeErrors if any of its arguments are invalid.
*/
export function createParse(
ownSecretKey: Uint8Array,
...peerPublicKeys: PeerPublicKey[]
): Parse {
if (!isValidSecretKey(ownSecretKey)) {
throw new TypeError("invalid secret key");
}
if (!peerPublicKeys.length) {
throw new TypeError("no peer public keys provided");
}
if (!peerPublicKeys.every(isValidPeerPublicKey)) {
throw new TypeError("invalid peer public keys");
}
const sharedKeyMap: Map<string, Uint8Array> = toSharedKeyMap(
ownSecretKey,
peerPublicKeys,
);
/**
* Parses the contents of a BWT token.
*
* token must be a BWT token.
*
* Returns null if the token is malformatted, corrupt, expired, from an
* unknown issuer, or if any other exceptions occur while marshalling, such as
* JSON.parse(body) -> 💥
*
* In case of a valid token parse returns an object containing the token
* header and body.
*
* This function encapsulates all validation and cryptographic verification of
* a token. Note that, as BWT requires every token to expire, parse does this
* basic metadata check.
*
* Additional application-specific metadata checks can be made as parse,
* besides the main body, returns the token header that contains metadata. Fx,
* an app could choose to reject all tokens of a certain age by additionally
* checking the mandatory iat claim of a token header.
*/
return function parse(token: string): null | Contents {
if (!hasValidTokenFormat(token)) {
return null;
}
let header: Header;
let body: Body;
try {
let kid: string;
let nonce: Uint8Array;
const parts: string[] = token.split(".");
const aad: Uint8Array = encode(parts[0], "base64url");
if (aad.byteLength > XCHACHA20_POLY1305_AAD_BYTES_MAX) {
return null;
}
[header, kid, nonce] = bufferToMetadata(aad);
const ciphertext: Uint8Array = encode(parts[1], "base64url");
if (ciphertext.byteLength > XCHACHA20_CIPHERTEXT_BYTES_MAX) {
return null;
}
const tag: Uint8Array = encode(parts[2], "base64url");
const sharedKey: undefined | Uint8Array = sharedKeyMap.get(kid);
if (!sharedKey) {
return null;
}
const plaintext: null | Uint8Array = open(
sharedKey,
nonce,
ciphertext,
aad,
tag,
);
if (!plaintext) {
return null;
}
const jsonPlaintext: string = decode(plaintext, "utf8");
plaintext.fill(0x00);
body = JSON.parse(jsonPlaintext);
} catch (_) {
return null;
}
if (!body || body.constructor !== Object || !isValidHeader(header)) {
return null;
}
return { header, body };
};
}