forked from panva/node-oidc-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprovider.js
399 lines (307 loc) · 11.6 KB
/
provider.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
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
// eslint-disable-next-line import/order
import * as attention from './helpers/attention.js';
import * as url from 'node:url';
import { strict as assert } from 'node:assert';
import * as events from 'node:events';
import Koa from 'koa';
import Configuration from './helpers/configuration.js';
import instance from './helpers/weak_cache.js';
import initializeKeystore from './helpers/initialize_keystore.js';
import initializeAdapter from './helpers/initialize_adapter.js';
import initializeApp from './helpers/initialize_app.js';
import initializeClients from './helpers/initialize_clients.js';
import RequestUriCache from './helpers/request_uri_cache.js';
import ResourceServer from './helpers/resource_server.js';
import { isWebUri } from './helpers/valid_url.js';
import epochTime from './helpers/epoch_time.js';
import getClaims from './helpers/claims.js';
import getContext from './helpers/oidc_context.js';
import { SessionNotFound, OIDCProviderError } from './helpers/errors.js';
import * as models from './models/index.js';
import * as ssHandler from './helpers/samesite_handler.js';
import get from './helpers/_/get.js';
import DPoPNonces from './helpers/dpop_nonces.js';
async function getInteraction(req, res) {
const ctx = this.app.createContext(req, res);
const id = ssHandler.get(
ctx.cookies,
this.cookieName('interaction'),
instance(this).configuration('cookies.short'),
);
if (!id) {
throw new SessionNotFound('interaction session id cookie not found');
}
const interaction = await this.Interaction.find(id);
if (!interaction) {
throw new SessionNotFound('interaction session not found');
}
if (interaction.session?.uid) {
const session = await this.Session.findByUid(interaction.session.uid);
if (!session) {
throw new SessionNotFound('session not found');
}
if (interaction.session.accountId !== session.accountId) {
throw new SessionNotFound('session principal changed');
}
}
return interaction;
}
class Provider extends events.EventEmitter {
#AccessToken;
#Account;
#app = new Koa();
#AuthorizationCode;
#BaseToken;
#Claims;
#Client;
#ClientCredentials;
#DeviceCode;
#BackchannelAuthenticationRequest;
#Grant;
#IdToken;
#InitialAccessToken;
#Interaction;
#mountPath;
#OIDCContext;
#PushedAuthorizationRequest;
#RefreshToken;
#RegistrationAccessToken;
#ReplayDetection;
#Session;
constructor(issuer, setup) {
assert(issuer, 'first argument must be the Issuer Identifier, i.e. https://op.example.com');
assert.equal(typeof issuer, 'string', 'Issuer Identifier must be a string');
assert(isWebUri(issuer), 'Issuer Identifier must be a valid web uri');
const components = url.parse(issuer);
assert(components.host, 'Issuer Identifier must have a host component');
assert(components.protocol, 'Issuer Identifier must have an URI scheme component');
assert(!components.search, 'Issuer Identifier must not have a query component');
assert(!components.hash, 'Issuer Identifier must not have a fragment component');
super();
this.issuer = issuer;
const configuration = new Configuration(setup);
instance(this).configuration = (path) => {
if (path) return get(configuration, path);
return configuration;
};
if (Array.isArray(configuration.cookies.keys) && configuration.cookies.keys.length) {
this.#app.keys = configuration.cookies.keys;
} else {
attention.warn('configuration cookies.keys is missing, this option is critical to detect and ignore tampered cookies');
}
if (configuration.features.dPoP.nonceSecret !== undefined) {
instance(this).DPoPNonces = new DPoPNonces(configuration.features.dPoP.nonceSecret);
}
instance(this).responseModes = new Map();
instance(this).grantTypeHandlers = new Map();
instance(this).grantTypeDupes = new Map();
instance(this).grantTypeParams = new Map([[undefined, new Set()]]);
this.#Account = { findAccount: configuration.findAccount };
this.#Claims = getClaims(this);
instance(this).BaseModel = models.getBaseModel(this);
this.#BaseToken = models.getBaseToken(this);
this.#IdToken = models.getIdToken(this);
this.#Client = models.getClient(this);
this.#Grant = models.getGrant(this);
this.#Session = models.getSession(this);
this.#Interaction = models.getInteraction(this);
this.#AccessToken = models.getAccessToken(this);
this.#AuthorizationCode = models.getAuthorizationCode(this);
this.#RefreshToken = models.getRefreshToken(this);
this.#ClientCredentials = models.getClientCredentials(this);
this.#InitialAccessToken = models.getInitialAccessToken(this);
this.#RegistrationAccessToken = models.getRegistrationAccessToken(this);
this.#ReplayDetection = models.getReplayDetection(this);
this.#DeviceCode = models.getDeviceCode(this);
this.#BackchannelAuthenticationRequest = models.getBackchannelAuthenticationRequest(this);
this.#PushedAuthorizationRequest = models.getPushedAuthorizationRequest(this);
this.#OIDCContext = getContext(this);
const { pathname } = url.parse(this.issuer);
this.#mountPath = pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;
instance(this).requestUriCache = new RequestUriCache(this);
initializeAdapter.call(this, configuration.adapter);
initializeKeystore.call(this, configuration.jwks);
delete configuration.jwks;
initializeApp.call(this);
initializeClients.call(this, configuration.clients);
delete configuration.clients;
}
urlFor(name, opt) { return url.resolve(this.issuer, this.pathFor(name, opt)); }
registerGrantType(name, handler, params, dupes) {
instance(this).configuration('grantTypes').add(name);
const { grantTypeHandlers, grantTypeParams, grantTypeDupes } = instance(this);
const grantParams = new Set(['grant_type']);
grantTypeHandlers.set(name, handler);
if (dupes && typeof dupes === 'string') {
grantTypeDupes.set(name, new Set([dupes]));
} else if (dupes && (Array.isArray(dupes) || dupes instanceof Set)) {
grantTypeDupes.set(name, new Set(dupes));
}
if (params && typeof params === 'string') {
grantParams.add(params);
} else if (params && (Array.isArray(params) || params instanceof Set)) {
params.forEach(Set.prototype.add.bind(grantParams));
}
grantTypeParams.set(name, grantParams);
grantParams.forEach(Set.prototype.add.bind(grantTypeParams.get(undefined)));
}
cookieName(type) {
const name = instance(this).configuration(`cookies.names.${type}`);
if (!name) {
throw new Error(`cookie name for type ${type} is not configured`);
}
return name;
}
registerResponseMode(name, handler) {
const { responseModes } = instance(this);
if (!responseModes.has(name)) {
responseModes.set(name, handler.bind(this));
}
}
pathFor(name, { mountPath = this.#mountPath, ...opts } = {}) {
const { router } = instance(this);
const routerUrl = router.url(name, opts);
if (routerUrl instanceof Error) {
throw routerUrl;
}
return [mountPath, routerUrl].join('');
}
/**
* @name interactionResult
* @api public
*/
async interactionResult(req, res, result, { mergeWithLastSubmission = true } = {}) {
const interaction = await getInteraction.call(this, req, res);
if (mergeWithLastSubmission && !('error' in result)) {
interaction.result = { ...interaction.lastSubmission, ...result };
} else {
interaction.result = result;
}
await interaction.save(interaction.exp - epochTime());
return interaction.returnTo;
}
/**
* @name interactionFinished
* @api public
*/
async interactionFinished(req, res, result, { mergeWithLastSubmission = true } = {}) {
const returnTo = await this.interactionResult(req, res, result, { mergeWithLastSubmission });
res.statusCode = 303; // eslint-disable-line no-param-reassign
res.setHeader('Location', returnTo);
res.setHeader('Content-Length', '0');
res.end();
}
/**
* @name interactionDetails
* @api public
*/
async interactionDetails(req, res) {
return getInteraction.call(this, req, res);
}
async backchannelResult(request, result, {
acr,
amr,
authTime,
sessionUid,
expiresWithSession,
sid,
} = {}) {
if (typeof request === 'string' && request) {
// eslint-disable-next-line no-param-reassign
request = await this.#BackchannelAuthenticationRequest.find(request, {
ignoreExpiration: true,
});
if (!request) {
throw new Error('BackchannelAuthenticationRequest not found');
}
} else if (!(request instanceof this.#BackchannelAuthenticationRequest)) {
throw new TypeError('invalid "request" argument');
}
const client = await this.#Client.find(request.clientId);
if (!client) {
throw new Error('Client not found');
}
if (typeof result === 'string' && result) {
// eslint-disable-next-line no-param-reassign
result = await this.#Grant.find(result);
if (!result) {
throw new Error('Grant not found');
}
}
switch (true) {
case result instanceof this.#Grant:
if (request.clientId !== result.clientId) {
throw new Error('client mismatch');
}
if (request.accountId !== result.accountId) {
throw new Error('accountId mismatch');
}
Object.assign(request, {
grantId: result.jti,
acr,
amr,
authTime,
sessionUid,
expiresWithSession,
sid,
});
break;
case result instanceof OIDCProviderError:
Object.assign(request, {
error: result.error,
error_description: result.error_description,
});
break;
default:
throw new TypeError('invalid "result" argument');
}
await request.save();
if (client.backchannelTokenDeliveryMode === 'ping') {
await client.backchannelPing(request);
}
}
use(fn) {
this.#app.use(fn);
// note: get the fn back since it might've been changed from generator to fn by koa-convert
const newMw = this.#app.middleware.pop();
const internalIndex = this.#app.middleware.findIndex((mw) => !!mw.firstInternal);
this.#app.middleware.splice(internalIndex, 0, newMw);
}
get app() {
return this.#app;
}
callback() {
return this.#app.callback();
}
listen(...args) {
return this.#app.listen(...args);
}
get proxy() {
return this.#app.proxy;
}
set proxy(value) {
this.#app.proxy = value;
}
get OIDCContext() { return this.#OIDCContext; }
get Claims() { return this.#Claims; }
get BaseToken() { return this.#BaseToken; }
get Account() { return this.#Account; }
get IdToken() { return this.#IdToken; }
get Client() { return this.#Client; }
get Grant() { return this.#Grant; }
get Session() { return this.#Session; }
get Interaction() { return this.#Interaction; }
get AccessToken() { return this.#AccessToken; }
get AuthorizationCode() { return this.#AuthorizationCode; }
get RefreshToken() { return this.#RefreshToken; }
get ClientCredentials() { return this.#ClientCredentials; }
get InitialAccessToken() { return this.#InitialAccessToken; }
get RegistrationAccessToken() { return this.#RegistrationAccessToken; }
get DeviceCode() { return this.#DeviceCode; }
get BackchannelAuthenticationRequest() { return this.#BackchannelAuthenticationRequest; }
get PushedAuthorizationRequest() { return this.#PushedAuthorizationRequest; }
get ReplayDetection() { return this.#ReplayDetection; }
// eslint-disable-next-line class-methods-use-this
get ResourceServer() { return ResourceServer; }
}
export default Provider;