/
server.ts
255 lines (231 loc) · 6.67 KB
/
server.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
/**
* Common logic for NodeJS HTTP servers.
*
* @module
*/
import { IncomingMessage } from 'http';
import {
Fief,
FiefAccessTokenACRTooLow,
FiefAccessTokenExpired,
FiefAccessTokenInfo,
FiefAccessTokenInvalid,
FiefAccessTokenMissingPermission,
FiefAccessTokenMissingScope,
FiefACR,
FiefError,
FiefUserInfo,
} from './client';
export class FiefAuthError extends FiefError { }
export class FiefAuthUnauthorized extends FiefAuthError { }
export class FiefAuthForbidden extends FiefAuthError { }
/**
* Type of a function that can be used to retrieve an access token.
*
* @param req — A NodeJS request object.
*
* @returns An access token or `null`.
*/
export type TokenGetter<RQ> = (req: RQ) => Promise<string | null>;
/**
* Interface that should follow a class to implement cache for user data.
*/
export interface IUserInfoCache {
/**
* Retrieve user information from cache, if available.
*
* @param id - ID of the user to retrieve the user information for.
*
* @returns User information or `null`.
*/
get(id: string): Promise<FiefUserInfo | null>;
/**
* Store user information in cache.
*
* @param id - ID of the user to store user information for.
* @param userinfo - The user information to store.
*
*/
set(id: string, userinfo: FiefUserInfo): Promise<void>;
/**
* Remove user information from cache.
*
* @param id - ID of the user to remove the user information for.
*
*/
remove(id: string): Promise<void>;
/**
* Clear all the user information from cache.
*/
clear(): Promise<void>;
}
/**
* Parameters to apply when authenticating a request.
*/
export interface AuthenticateRequestParameters {
/**
* If `false` and the request is not authenticated,
* a {@link FiefAuthUnauthorized} error will be raised.
*/
optional?: boolean;
/**
* Optional list of scopes required.
* If the access token lacks one of the required scope,
* a {@link FiefAuthForbidden} error will be raised.
*/
scope?: string[];
/**
* Optional minimum ACR level required.
* If the access token doesn't meet the minimum level,
* a {@link FiefAccessTokenACRTooLow} error will be raised.
*/
acr?: FiefACR;
/**
* Optional list of permissions required.
* If the access token lacks one of the required permission,
* a {@link FiefAuthForbidden} error will be raised.
*/
permissions?: string[];
/**
* If `true`, the user information will be refreshed from the Fief API.
* Otherwise, the cache will be used.
*/
refresh?: boolean;
}
/**
* Data returned after a request has been successfully authenticated.
*/
export interface AuthenticateRequestResult {
/**
* Information about the current access token.
*/
accessTokenInfo: FiefAccessTokenInfo | null;
/**
* Current user information.
*/
user: FiefUserInfo | null;
}
/**
* Class implementing common logic for authenticating requests in NodeJS servers.
*/
export class FiefAuth<RQ> {
private client: Fief;
private tokenGetter: TokenGetter<RQ>;
private userInfoCache?: IUserInfoCache;
/**
* @param client - Instance of a {@link Fief} client.
* @param tokenGetter - A {@link TokenGetter} function.
* @param userInfoCache - An instance of a {@link IUserInfoCache} class.
*/
constructor(client: Fief, tokenGetter: TokenGetter<RQ>, userInfoCache?: IUserInfoCache) {
this.client = client;
this.tokenGetter = tokenGetter;
this.userInfoCache = userInfoCache;
}
/**
* Factory to generate handler for authenticating NodeJS requests.
*
* @param parameters - Parameters to apply when authenticating the request.
*
* @returns A handler to authenticate NodeJS requests.
*/
public authenticate(parameters: AuthenticateRequestParameters) {
return async (req: RQ): Promise<AuthenticateRequestResult> => {
const {
optional,
scope,
acr,
permissions,
refresh,
} = parameters;
const token = await this.tokenGetter(req);
if (token === null && optional !== true) {
throw new FiefAuthUnauthorized();
}
let accessTokenInfo: FiefAccessTokenInfo | null = null;
let user: FiefUserInfo | null = null;
if (token !== null) {
try {
accessTokenInfo = await this.client.validateAccessToken(
token,
scope,
acr,
permissions,
);
if (this.userInfoCache) {
user = await this.userInfoCache.get(accessTokenInfo.id);
if (user === null || refresh === true) {
user = await this.client.userinfo(accessTokenInfo.access_token);
await this.userInfoCache.set(accessTokenInfo.id, user);
}
}
} catch (err) {
if (
!optional
&& (err instanceof FiefAccessTokenInvalid || err instanceof FiefAccessTokenExpired)
) {
throw new FiefAuthUnauthorized();
} else if (
err instanceof FiefAccessTokenMissingScope
|| err instanceof FiefAccessTokenACRTooLow
|| err instanceof FiefAccessTokenMissingPermission
) {
throw new FiefAuthForbidden();
} else {
throw err;
}
}
}
return { accessTokenInfo, user };
};
}
}
/**
* Return a {@link TokenGetter} function retrieving a token
* from the `Authorization` header of an HTTP request
* with the specified scheme.
*
* @param scheme - Scheme of the token. Defaults to `bearer`.
*
* @returns A {@link TokenGetter} function.
*/
export const authorizationSchemeGetter = (scheme: string = 'bearer'): TokenGetter<IncomingMessage> => async (
req: IncomingMessage,
) => {
const { authorization } = req.headers;
if (authorization === undefined) {
return null;
}
const parts = authorization.split(' ');
if (parts.length !== 2 || parts[0].toLowerCase() !== scheme) {
return null;
}
return parts[1];
};
/**
* Return a {@link TokenGetter} function retrieving a token
* from a `Cookie` of an HTTP request.
*
* @param cookieName - Name of the cookie.
*
* @returns A {@link TokenGetter} function.
*/
export const cookieGetter = (cookieName: string): TokenGetter<IncomingMessage> => async (
req: IncomingMessage,
) => {
const { cookie: cookieHeader } = req.headers;
if (cookieHeader === undefined) {
return null;
}
const cookies = cookieHeader.split(';');
for (let i = 0; i < cookies.length; i += 1) {
const cookie = cookies[i].trim();
const semicolonIndex = cookie.indexOf('=');
const name = cookie.slice(0, semicolonIndex);
const value = cookie.slice(semicolonIndex + 1);
if (name === cookieName) {
return value;
}
}
return null;
};