-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMsApiClient.ts
161 lines (138 loc) · 4.19 KB
/
MsApiClient.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
import { buildUrl } from 'build-url-ts';
type Secrets = {
tenantId: string;
clientId: string;
clientSecret: string;
};
type StateManagement = {
newState: (state: string) => void | Promise<void>;
stateExists: (state: string) => boolean | Promise<boolean>;
removeState: (state: string) => void | Promise<void>;
};
// https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow
// Todo: custom errors
export class MsAuthClient {
msAuthEndpoint: string;
scopeUrls: string[];
statesTail = -1;
// We only want to ensure the request originated from our website,
// hence no identifiable information. An in memory array as your request
// should be done pretty fast + we have a maxStates variable.
states = [] as (string | undefined)[];
constructor(
private scopes: string[],
private secrets: Secrets,
private redirectUri: string,
private stateManager: StateManagement = {
newState: state => {
this.statesTail = (this.statesTail + 1) % 200;
this.states[this.statesTail] = state;
},
stateExists: state => this.states.indexOf(state) != -1,
removeState: state => {
const index = this.states.indexOf(state);
this.states[index] = undefined;
}
}
) {
this.msAuthEndpoint = `https://login.microsoftonline.com/${secrets.tenantId}/oauth2/v2.0`;
this.scopeUrls = this.scopes.map(
val => `https://graph.microsoft.com/${val}`
);
}
public getRedirectUrl(state?: string): string {
const _state = state || crypto.randomUUID();
this.stateManager.newState(_state);
const url = buildUrl(this.msAuthEndpoint, {
path: '/authorize',
queryParams: {
client_id: this.secrets.clientId,
redirect_uri: this.redirectUri,
scope: this.scopeUrls.join(' '),
state: _state,
response_type: 'code',
response_mode: 'query',
prompt: 'consent'
}
});
return url;
}
public async verifyAndConsumeCode(code: string, state: string) {
const validState = this.stateManager.stateExists(state);
if (!validState) {
throw new Error(`Failed to verify code: Mismatched state.`);
}
this.stateManager.removeState(state);
const req = await fetch(`${this.msAuthEndpoint}/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
client_id: this.secrets.clientId,
scope: this.scopeUrls.join(' '),
code: code,
redirect_uri: this.redirectUri,
grant_type: 'authorization_code',
client_secret: this.secrets.clientSecret
}).toString()
});
const res = await req.json();
if (res.error)
throw new Error(`Failed to verify code:\n ${res.error_description}`);
return new MicrosoftGraphClient(
res.access_token,
res.refresh_token || null,
res.expires_in,
res.scope
);
}
}
export class MicrosoftGraphClient {
public expiresAt: Date;
private baseUrl = 'https://graph.microsoft.com/v1.0';
public constructor(
public access_token: string,
public refresh_token: string | null,
expires_in: number,
public scope: string
) {
this.expiresAt = new Date();
this.expiresAt.setSeconds(this.expiresAt.getSeconds() + expires_in);
}
public async get<K extends string>(
path: string,
select?: K[]
): Promise<Record<K, string>> {
const selectQuery =
select == null
? undefined
: {
$select: select.join(',')
};
const url = buildUrl(this.baseUrl, {
path: path,
queryParams: selectQuery
});
const req = await fetch(url, {
headers: {
Authorization: this.access_token,
'Content-Type': 'application/json'
}
});
const res = await req.json();
if (res.error) {
throw new Error(`Microsoft Graph error:\n${res.error_description}`);
}
if (!select) {
return res as Record<K, any>;
} else {
const toRet: Partial<Record<K, any>> = {};
select.forEach(key => {
toRet[key] = res[key];
});
return res as Record<K, any>;
}
// TODO: check if call failed, select failed, etc.
}
}