forked from panva/node-oidc-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrefresh_token.js
271 lines (221 loc) · 8.02 KB
/
refresh_token.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
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
import difference from '../../helpers/_/difference.js';
import { InvalidRequest, InvalidGrant, InvalidScope } from '../../helpers/errors.js';
import presence from '../../helpers/validate_presence.js';
import instance from '../../helpers/weak_cache.js';
import revoke from '../../helpers/revoke.js';
import certificateThumbprint from '../../helpers/certificate_thumbprint.js';
import * as formatters from '../../helpers/formatters.js';
import filterClaims from '../../helpers/filter_claims.js';
import dpopValidate, { DPOP_OK_WINDOW } from '../../helpers/validate_dpop.js';
import resolveResource from '../../helpers/resolve_resource.js';
import epochTime from '../../helpers/epoch_time.js';
import checkRar from '../../shared/check_rar.js';
import { gty as cibaGty } from './ciba.js';
import { gty as deviceCodeGty } from './device_code.js';
function rarSupported(token) {
const [origin] = token.gty.split(' ');
return origin !== cibaGty && origin !== deviceCodeGty;
}
const gty = 'refresh_token';
export const handler = async function refreshTokenHandler(ctx, next) {
presence(ctx, 'refresh_token');
const conf = instance(ctx.oidc.provider).configuration();
const {
conformIdTokenClaims,
rotateRefreshToken,
features: {
userinfo,
mTLS: { getCertificate },
dPoP: { allowReplay },
resourceIndicators,
richAuthorizationRequests,
},
} = conf;
const {
RefreshToken, Account, AccessToken, IdToken, ReplayDetection,
} = ctx.oidc.provider;
const { client } = ctx.oidc;
const dPoP = await dpopValidate(ctx);
let refreshTokenValue = ctx.oidc.params.refresh_token;
let refreshToken = await RefreshToken.find(refreshTokenValue, { ignoreExpiration: true });
if (!refreshToken) {
throw new InvalidGrant('refresh token not found');
}
if (refreshToken.clientId !== client.clientId) {
throw new InvalidGrant('client mismatch');
}
if (refreshToken.isExpired) {
throw new InvalidGrant('refresh token is expired');
}
let cert;
if (client.tlsClientCertificateBoundAccessTokens || refreshToken['x5t#S256']) {
cert = getCertificate(ctx);
if (!cert) {
throw new InvalidGrant('mutual TLS client certificate not provided');
}
}
if (!dPoP && ctx.oidc.client.dpopBoundAccessTokens) {
throw new InvalidGrant('DPoP proof JWT not provided');
}
if (refreshToken['x5t#S256'] && refreshToken['x5t#S256'] !== certificateThumbprint(cert)) {
throw new InvalidGrant('failed x5t#S256 verification');
}
const grant = await ctx.oidc.provider.Grant.find(refreshToken.grantId, {
ignoreExpiration: true,
});
if (!grant) {
throw new InvalidGrant('grant not found');
}
if (grant.isExpired) {
throw new InvalidGrant('grant is expired');
}
if (grant.clientId !== client.clientId) {
throw new InvalidGrant('client mismatch');
}
if (ctx.oidc.params.scope) {
const missing = difference([...ctx.oidc.requestParamScopes], [...refreshToken.scopes]);
if (missing.length !== 0) {
throw new InvalidScope(`refresh token missing requested ${formatters.pluralize('scope', missing.length)}`, missing.join(' '));
}
}
if (dPoP && !allowReplay) {
const unique = await ReplayDetection.unique(
client.clientId,
dPoP.jti,
epochTime() + DPOP_OK_WINDOW,
);
ctx.assert(unique, new InvalidGrant('DPoP proof JWT Replay detected'));
}
if (refreshToken.jkt && (!dPoP || refreshToken.jkt !== dPoP.thumbprint)) {
throw new InvalidGrant('failed jkt verification');
}
ctx.oidc.entity('RefreshToken', refreshToken);
ctx.oidc.entity('Grant', grant);
const account = await Account.findAccount(ctx, refreshToken.accountId, refreshToken);
if (!account) {
throw new InvalidGrant('refresh token invalid (referenced account not found)');
}
if (refreshToken.accountId !== grant.accountId) {
throw new InvalidGrant('accountId mismatch');
}
ctx.oidc.entity('Account', account);
if (refreshToken.consumed) {
await Promise.all([
refreshToken.destroy(),
revoke(ctx, refreshToken.grantId),
]);
throw new InvalidGrant('refresh token already used');
}
if (ctx.oidc.params.authorization_details && !rarSupported(refreshToken)) {
throw new InvalidRequest('authorization_details is unsupported for this refresh token');
}
if (
rotateRefreshToken === true
|| (typeof rotateRefreshToken === 'function' && await rotateRefreshToken(ctx))
) {
await refreshToken.consume();
ctx.oidc.entity('RotatedRefreshToken', refreshToken);
refreshToken = new RefreshToken({
accountId: refreshToken.accountId,
acr: refreshToken.acr,
amr: refreshToken.amr,
authTime: refreshToken.authTime,
claims: refreshToken.claims,
client,
expiresWithSession: refreshToken.expiresWithSession,
iiat: refreshToken.iiat,
grantId: refreshToken.grantId,
gty: refreshToken.gty,
nonce: refreshToken.nonce,
resource: refreshToken.resource,
rotations: typeof refreshToken.rotations === 'number' ? refreshToken.rotations + 1 : 1,
scope: refreshToken.scope,
sessionUid: refreshToken.sessionUid,
sid: refreshToken.sid,
rar: refreshToken.rar,
'x5t#S256': refreshToken['x5t#S256'],
jkt: refreshToken.jkt,
});
if (refreshToken.gty && !refreshToken.gty.endsWith(gty)) {
refreshToken.gty = `${refreshToken.gty} ${gty}`;
}
ctx.oidc.entity('RefreshToken', refreshToken);
refreshTokenValue = await refreshToken.save();
}
const at = new AccessToken({
accountId: account.accountId,
client,
expiresWithSession: refreshToken.expiresWithSession,
grantId: refreshToken.grantId,
gty: refreshToken.gty,
sessionUid: refreshToken.sessionUid,
sid: refreshToken.sid,
});
if (client.tlsClientCertificateBoundAccessTokens) {
at.setThumbprint('x5t', cert);
}
if (dPoP) {
at.setThumbprint('jkt', dPoP.thumbprint);
}
if (at.gty && !at.gty.endsWith(gty)) {
at.gty = `${at.gty} ${gty}`;
}
const scope = ctx.oidc.params.scope ? ctx.oidc.requestParamScopes : refreshToken.scopes;
await checkRar(ctx, () => {});
const resource = await resolveResource(
ctx,
refreshToken,
{ userinfo, resourceIndicators },
scope,
);
if (resource) {
const resourceServerInfo = await resourceIndicators
.getResourceServerInfo(ctx, resource, ctx.oidc.client);
at.resourceServer = new ctx.oidc.provider.ResourceServer(resource, resourceServerInfo);
at.scope = grant.getResourceScopeFiltered(
resource,
[...scope].filter(Set.prototype.has.bind(at.resourceServer.scopes)),
);
} else {
at.claims = refreshToken.claims;
at.scope = grant.getOIDCScopeFiltered(scope);
}
if (richAuthorizationRequests.enabled && at.resourceServer) {
at.rar = await richAuthorizationRequests.rarForRefreshTokenResponse(ctx, at.resourceServer);
}
ctx.oidc.entity('AccessToken', at);
const accessToken = await at.save();
let idToken;
if (scope.has('openid')) {
const claims = filterClaims(refreshToken.claims, 'id_token', grant);
const rejected = grant.getRejectedOIDCClaims();
const token = new IdToken(({
...await account.claims('id_token', [...scope].join(' '), claims, rejected),
acr: refreshToken.acr,
amr: refreshToken.amr,
auth_time: refreshToken.authTime,
}), { ctx });
if (conformIdTokenClaims && userinfo.enabled && !at.aud) {
token.scope = 'openid';
} else {
token.scope = grant.getOIDCScopeFiltered(scope);
}
token.mask = claims;
token.rejected = rejected;
token.set('nonce', refreshToken.nonce);
token.set('at_hash', accessToken);
token.set('sid', refreshToken.sid);
idToken = await token.issue({ use: 'idtoken' });
}
ctx.body = {
access_token: accessToken,
expires_in: at.expiration,
id_token: idToken,
refresh_token: refreshTokenValue,
scope: refreshToken.scope ? at.scope : (at.scope || undefined),
token_type: at.tokenType,
authorization_details: at.rar,
};
await next();
};
export const parameters = new Set(['refresh_token', 'scope']);