-
-
Notifications
You must be signed in to change notification settings - Fork 387
/
client.js
228 lines (199 loc) · 6.41 KB
/
client.js
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
const jose = require('jose');
const { RPError } = require('../errors');
const { assertIssuerConfiguration } = require('./assert');
const { random } = require('./generators');
const now = require('./unix_timestamp');
const request = require('./request');
const { keystores } = require('./weak_cache');
const merge = require('./merge');
function formUrlEncode(token) {
return encodeURIComponent(token).replace(/(?:[-_.!~*'()]|%20)/g, (substring) => {
switch (substring) {
case '-':
case '_':
case '.':
case '!':
case '~':
case '*':
case "'":
case '(':
case ')':
return `%${substring.charCodeAt(0).toString(16).toUpperCase()}`;
case '%20':
return '+';
default:
throw new Error();
}
});
}
async function clientAssertion(endpoint, payload) {
let alg = this[`${endpoint}_endpoint_auth_signing_alg`];
if (!alg) {
assertIssuerConfiguration(
this.issuer,
`${endpoint}_endpoint_auth_signing_alg_values_supported`,
);
}
if (this[`${endpoint}_endpoint_auth_method`] === 'client_secret_jwt') {
if (!alg) {
const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`];
alg =
Array.isArray(supported) && supported.find((signAlg) => /^HS(?:256|384|512)/.test(signAlg));
}
if (!alg) {
throw new RPError(
`failed to determine a JWS Algorithm to use for ${
this[`${endpoint}_endpoint_auth_method`]
} Client Assertion`,
);
}
return new jose.CompactSign(Buffer.from(JSON.stringify(payload)))
.setProtectedHeader({ alg })
.sign(this.secretForAlg(alg));
}
const keystore = await keystores.get(this);
if (!keystore) {
throw new TypeError('no client jwks provided for signing a client assertion with');
}
if (!alg) {
const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`];
alg =
Array.isArray(supported) &&
supported.find((signAlg) => keystore.get({ alg: signAlg, use: 'sig' }));
}
if (!alg) {
throw new RPError(
`failed to determine a JWS Algorithm to use for ${
this[`${endpoint}_endpoint_auth_method`]
} Client Assertion`,
);
}
const key = keystore.get({ alg, use: 'sig' });
if (!key) {
throw new RPError(
`no key found in client jwks to sign a client assertion with using alg ${alg}`,
);
}
return new jose.CompactSign(Buffer.from(JSON.stringify(payload)))
.setProtectedHeader({ alg, kid: key.jwk && key.jwk.kid })
.sign(await key.keyObject(alg));
}
async function authFor(endpoint, { clientAssertionPayload } = {}) {
const authMethod = this[`${endpoint}_endpoint_auth_method`];
switch (authMethod) {
case 'self_signed_tls_client_auth':
case 'tls_client_auth':
case 'none':
return { form: { client_id: this.client_id } };
case 'client_secret_post':
if (typeof this.client_secret !== 'string') {
throw new TypeError(
'client_secret_post client authentication method requires a client_secret',
);
}
return { form: { client_id: this.client_id, client_secret: this.client_secret } };
case 'private_key_jwt':
case 'client_secret_jwt': {
const timestamp = now();
const audience = [
...new Set([this.issuer.issuer, this.issuer.token_endpoint].filter(Boolean)),
];
const assertion = await clientAssertion.call(this, endpoint, {
iat: timestamp,
exp: timestamp + 60,
jti: random(),
iss: this.client_id,
sub: this.client_id,
aud: audience,
...clientAssertionPayload,
});
return {
form: {
client_id: this.client_id,
client_assertion: assertion,
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
},
};
}
case 'client_secret_basic': {
// This is correct behaviour, see https://tools.ietf.org/html/rfc6749#section-2.3.1 and the
// related appendix. (also https://github.com/panva/node-openid-client/pull/91)
// > The client identifier is encoded using the
// > "application/x-www-form-urlencoded" encoding algorithm per
// > Appendix B, and the encoded value is used as the username; the client
// > password is encoded using the same algorithm and used as the
// > password.
if (typeof this.client_secret !== 'string') {
throw new TypeError(
'client_secret_basic client authentication method requires a client_secret',
);
}
const encoded = `${formUrlEncode(this.client_id)}:${formUrlEncode(this.client_secret)}`;
const value = Buffer.from(encoded).toString('base64');
return { headers: { Authorization: `Basic ${value}` } };
}
default: {
throw new TypeError(`missing, or unsupported, ${endpoint}_endpoint_auth_method`);
}
}
}
function resolveResponseType() {
const { length, 0: value } = this.response_types;
if (length === 1) {
return value;
}
return undefined;
}
function resolveRedirectUri() {
const { length, 0: value } = this.redirect_uris || [];
if (length === 1) {
return value;
}
return undefined;
}
async function authenticatedPost(
endpoint,
opts,
{ clientAssertionPayload, endpointAuthMethod = endpoint, DPoP } = {},
) {
const auth = await authFor.call(this, endpointAuthMethod, { clientAssertionPayload });
const requestOpts = merge(opts, auth);
const mTLS =
this[`${endpointAuthMethod}_endpoint_auth_method`].includes('tls_client_auth') ||
(endpoint === 'token' && this.tls_client_certificate_bound_access_tokens);
let targetUrl;
if (mTLS && this.issuer.mtls_endpoint_aliases) {
targetUrl = this.issuer.mtls_endpoint_aliases[`${endpoint}_endpoint`];
}
targetUrl = targetUrl || this.issuer[`${endpoint}_endpoint`];
if ('form' in requestOpts) {
for (const [key, value] of Object.entries(requestOpts.form)) {
if (typeof value === 'undefined') {
delete requestOpts.form[key];
}
}
}
return request.call(
this,
{
...requestOpts,
method: 'POST',
url: targetUrl,
headers: {
...(endpoint !== 'revocation'
? {
Accept: 'application/json',
}
: undefined),
...requestOpts.headers,
},
},
{ mTLS, DPoP },
);
}
module.exports = {
resolveResponseType,
resolveRedirectUri,
authFor,
authenticatedPost,
};