This repository has been archived by the owner on Jun 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
244 lines (203 loc) · 6.89 KB
/
index.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
/**
* @module smart-auth
* @beta
*
* A Fastify plugin to support the SMART App Authorization response code authorization OAuth 2.0 flow and wrapping the simple-oauth2 library.
*/
import { randomBytes } from "crypto";
import { AccessToken, AuthorizationCode, ClientCredentials } from "simple-oauth2";
import { FastifyPluginCallback, FastifyReply, FastifyRequest } from "fastify";
import fastifyPlugin from "fastify-plugin";
// @todo this should come from @types/fhir - and specifically fhir3.FhirResourceList but it
// hasn't been released yet - we use our deprecated enum
import FHIRResourceList from "../resources";
type LaunchContext = "launch" | "launch/patient"
type Profile = "openid" | "fhirUser" | "profile"
type Refresh = "online_access" | "offline_access"
type Resources = `${"patient" | "user"}/${FHIRResourceList | "*"}.${"read" | "write" | "*"}`
export type SmartAuthScope = LaunchContext | Profile | Refresh | Resources
export type GrantFlow = "authorization_code" | "client_credentials"
export interface SmartAuthProvider<T = AuthCodeConfig | ClientCredentialsConfig> {
/** A name to label the provider */
name: string;
/** Client registration */
client: {
id: string;
secret: string;
};
/** Auth related config */
auth: T;
}
export interface SmartAuthConfig {
/** Supported grant flow */
grantFlow: GrantFlow;
/** String used to set the host to request the tokens to. Required. */
tokenHost: string;
/** String path to request an access token. Default to /oauth/token. */
tokenPath?: string;
/** Optional params to post to the token exchange */
tokenParams?: Record<string, any>;
}
export interface ClientCredentialsConfig extends SmartAuthConfig {
grantFlow: "client_credentials"
};
export interface AuthCodeConfig extends SmartAuthConfig {
grantFlow: "authorization_code"
scope: SmartAuthScope[];
/** An optional prefix to add to every route path */
pathPrefix?: string;
/** Optional params to append to the authorization redirect */
authorizeParams?: Record<string, any>;
/** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */
authorizeHost?: string;
/** String path to request an authorization code. Default to /oauth/authorize. */
authorizePath?: string;
/** String path to revoke an access token. Default to /oauth/revoke. */
revokePath?: string;
/** Where should users (with the auth code) be redirected to? */
redirect: {
/** A required host name for the auth code exchange redirect path. */
host: string;
/** An optional authorize path override. */
path?: string;
};
};
export interface SmartAuthNamespace {
authorizationCodeFlow: AuthorizationCode;
getAccessTokenFromAuthorizationCodeFlow(
request: FastifyRequest<SmartAuthRedirectQuerystring>,
): Promise<AccessToken>;
getAccessTokenFromClientCredentialFlow(
smartAuthProvider: SmartAuthProvider,
scope?: string[],
): Promise<AccessToken>;
getNewAccessTokenUsingRefreshToken(
refreshToken: string,
params: Record<string, any>
): Promise<AccessToken>;
generateAuthorizationUri(
scope?: SmartAuthScope[],
): string;
}
export const SmartAuthRedirectQuerystringSchema = {
schema: {
querystring: {
code: { type: 'string' },
state: { type: 'string', }
}
}
}
export interface SmartAuthRedirectQuerystring {
Querystring: {
code: string,
state: string
}
}
export interface SmartAuthUrlQuerystring {
Querystring?: {
scope?: SmartAuthScope[]
}
}
const defaultState = randomBytes(10).toString('hex')
function generateState(): string {
return defaultState;
}
function checkState(state: string) {
if (state === defaultState) return
new Error('Invalid state')
}
function routeCase(value: string): string {
return value.toLowerCase().replace(/\s/g,'-');
}
const oauthPlugin: FastifyPluginCallback<SmartAuthProvider<AuthCodeConfig>> = function (http, options, next) {
const { name, client } = options;
const auth = options.auth;
const { scope: defaultScope, redirect } = auth;
const prefix = auth?.pathPrefix || "/smart";
const tokenParams = auth?.tokenParams || {}
const tokenHost = auth.tokenHost;
const authorizeParams = auth?.authorizeParams || {}
const authorizeRedirectPath = `${prefix}/${routeCase(name)}/auth`
const redirectPath = redirect?.path || `${prefix}/${routeCase(name)}/redirect`
const redirectUri = `${redirect.host}${redirectPath}`
function generateAuthorizationUri(scope?: SmartAuthScope[]) {
const state = generateState();
const urlOptions = Object.assign({}, authorizeParams, {
redirect_uri: redirectUri,
scope: scope || defaultScope,
state
})
const authorizationUri = authorizationCodeFlow.authorizeURL(urlOptions)
return authorizationUri
}
function startRedirect(
request: FastifyRequest<SmartAuthUrlQuerystring>,
reply: FastifyReply
) {
const authorizationUri = generateAuthorizationUri(request?.query?.scope)
reply.redirect(authorizationUri);
}
async function getAccessTokenFromAuthorizationCodeFlow(
this: SmartAuthNamespace,
request: FastifyRequest<SmartAuthRedirectQuerystring>
): Promise<AccessToken> {
const { code, state } = request.query;
checkState(state);
const params = Object.assign({}, tokenParams, {
code: code,
redirect_uri: redirectUri
})
return await this.authorizationCodeFlow.getToken(params)
}
async function getNewAccessTokenUsingRefreshToken(
this: SmartAuthNamespace,
refreshToken: string
): Promise<AccessToken> {
return await this.authorizationCodeFlow.createToken({ refresh_token: refreshToken }).refresh()
}
const authCodeOptions = {
client,
auth: {
tokenPath: auth?.tokenPath,
revokePath: auth?.revokePath,
authorizeHost: auth?.authorizeHost,
authorizePath: auth?.authorizePath,
tokenHost
}
}
const authorizationCodeFlow = new AuthorizationCode(authCodeOptions)
http.get(authorizeRedirectPath, startRedirect)
try {
http.decorate(name, {
authorizationCodeFlow,
getAccessTokenFromAuthorizationCodeFlow,
getNewAccessTokenUsingRefreshToken,
generateAuthorizationUri
})
} catch (e) {
next(e as Error)
return
}
next();
}
export const getAccessTokenFromClientCredentialFlow = async (
smartAuthProvider: SmartAuthProvider<ClientCredentialsConfig>,
scope?: string[]
): Promise<AccessToken> => {
const clientCredentialsOptions = {
client: smartAuthProvider.client,
auth: {
tokenPath: smartAuthProvider.auth?.tokenPath,
tokenHost: smartAuthProvider.auth?.tokenHost
},
};
const client = new ClientCredentials(clientCredentialsOptions);
const params = {
scope,
...smartAuthProvider.auth.tokenParams
}
return await client.getToken(params);
};
export default fastifyPlugin(oauthPlugin, {
name: "smart-auth"
})