forked from authts/oidc-client-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptoUtils.ts
More file actions
254 lines (228 loc) · 7.8 KB
/
Copy pathCryptoUtils.ts
File metadata and controls
254 lines (228 loc) · 7.8 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
import { Logger } from "./Logger";
import { JwtUtils } from "./JwtUtils";
export interface GenerateDPoPProofOpts {
url: string;
accessToken?: string;
httpMethod?: string;
keyPair: CryptoKeyPair;
nonce?: string;
}
const UUID_V4_TEMPLATE = "10000000-1000-4000-8000-100000000000";
const toBase64 = (val: ArrayBuffer | Uint8Array): string =>
btoa([...new Uint8Array(val)]
.map((chr) => String.fromCharCode(chr))
.join(""));
/**
* @internal
*/
export class CryptoUtils {
private static _randomWord(): number {
const arr = new Uint32Array(1);
crypto.getRandomValues(arr);
return arr[0];
}
/**
* Generates RFC4122 version 4 guid
*/
public static generateUUIDv4(): string {
const uuid = UUID_V4_TEMPLATE.replace(/[018]/g, c =>
(+c ^ CryptoUtils._randomWord() & 15 >> +c / 4).toString(16),
);
return uuid.replace(/-/g, "");
}
/**
* PKCE: Generate a code verifier
*/
public static generateCodeVerifier(): string {
return CryptoUtils.generateUUIDv4() + CryptoUtils.generateUUIDv4() + CryptoUtils.generateUUIDv4();
}
/**
* PKCE: Generate a code challenge
*/
public static async generateCodeChallenge(code_verifier: string): Promise<string> {
if (!crypto.subtle) {
throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");
}
try {
const encoder = new TextEncoder();
const data = encoder.encode(code_verifier);
const hashed = await crypto.subtle.digest("SHA-256", data);
return toBase64(hashed).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
catch (err) {
Logger.error("CryptoUtils.generateCodeChallenge", err);
throw err;
}
}
/**
* Generates a base64-encoded string for a basic auth header
*/
public static generateBasicAuth(client_id: string, client_secret: string): string {
const encoder = new TextEncoder();
const data = encoder.encode([client_id, client_secret].join(":"));
return toBase64(data);
}
/**
* Generates a hash of a string using a given algorithm
* @param alg
* @param message
*/
public static async hash(alg: string, message: string) : Promise<Uint8Array> {
const msgUint8 = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest(alg, msgUint8);
return new Uint8Array(hashBuffer);
}
/**
* Generates a base64url encoded string
*/
public static encodeBase64Url = (input: Uint8Array) => {
return toBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
};
/**
* Generates a rfc7638 compliant jwk thumbprint
* @param jwk
*/
public static async customCalculateJwkThumbprint(jwk: JsonWebKey): Promise<string> {
let jsonObject: object;
switch (jwk.kty) {
case "RSA":
jsonObject = {
"e": jwk.e,
"kty": jwk.kty,
"n": jwk.n,
};
break;
case "EC":
jsonObject = {
"crv": jwk.crv,
"kty": jwk.kty,
"x": jwk.x,
"y": jwk.y,
};
break;
case "OKP":
jsonObject = {
"crv": jwk.crv,
"kty": jwk.kty,
"x": jwk.x,
};
break;
case "oct":
jsonObject = {
"crv": jwk.k,
"kty": jwk.kty,
};
break;
default:
throw new Error("Unknown jwk type");
}
const utf8encodedAndHashed = await CryptoUtils.hash("SHA-256", JSON.stringify(jsonObject));
return CryptoUtils.encodeBase64Url(utf8encodedAndHashed);
}
public static async generateDPoPProof({
url,
accessToken,
httpMethod,
keyPair,
nonce,
}: GenerateDPoPProofOpts): Promise<string> {
let hashedToken: Uint8Array;
let encodedHash: string;
const payload: Record<string, string | number> = {
"jti": window.crypto.randomUUID(),
"htm": httpMethod ?? "GET",
"htu": url,
"iat": Math.floor(Date.now() / 1000),
};
if (accessToken) {
hashedToken = await CryptoUtils.hash("SHA-256", accessToken);
encodedHash = CryptoUtils.encodeBase64Url(hashedToken);
payload.ath = encodedHash;
}
if (nonce) {
payload.nonce = nonce;
}
try {
const publicJwk = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
const header = {
"alg": "ES256",
"typ": "dpop+jwt",
"jwk": {
"crv": publicJwk.crv,
"kty": publicJwk.kty,
"x": publicJwk.x,
"y": publicJwk.y,
},
};
return await JwtUtils.generateSignedJwt(header, payload, keyPair.privateKey);
} catch (err) {
if (err instanceof TypeError) {
throw new Error(`Error exporting dpop public key: ${err.message}`);
} else {
throw err;
}
}
}
public static async generateDPoPJkt(keyPair: CryptoKeyPair) : Promise<string> {
try {
const publicJwk = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
return await CryptoUtils.customCalculateJwkThumbprint(publicJwk);
} catch (err) {
if (err instanceof TypeError) {
throw new Error(`Could not retrieve dpop keys from storage: ${err.message}`);
} else {
throw err;
}
}
}
public static async generateDPoPKeys() : Promise<CryptoKeyPair> {
return await window.crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-256",
},
false,
["sign", "verify"],
);
}
/**
* Generates a client assertion JWT for client_secret_jwt authentication
* @param client_id The client identifier
* @param client_secret The client secret
* @param audience The token endpoint URL (audience)
* @param algorithm The HMAC algorithm to use (HS256, HS384, HS512). Defaults to HS256
*/
public static async generateClientAssertionJwt(client_id: string, client_secret: string, audience: string, algorithm: string = "HS256"): Promise<string> {
const now = Math.floor(Date.now() / 1000);
const header = {
"alg": algorithm,
"typ": "JWT",
};
const payload = {
"iss": client_id,
"sub": client_id,
"aud": audience,
"jti": CryptoUtils.generateUUIDv4(),
"exp": now + 300, // 5 minutes
"iat": now,
};
const hashMap: Record<string, string> = {
"HS256": "SHA-256",
"HS384": "SHA-384",
"HS512": "SHA-512",
};
const hashFunction = hashMap[algorithm];
if (!hashFunction) {
throw new Error(`Unsupported algorithm: ${algorithm}. Supported algorithms are: HS256, HS384, HS512`);
}
const encoder = new TextEncoder();
const secretKey = await crypto.subtle.importKey(
"raw",
encoder.encode(client_secret),
{ name: "HMAC", hash: hashFunction },
false,
["sign"],
);
return await JwtUtils.generateSignedJwtWithHmac(header, payload, secretKey);
}
}