-
Notifications
You must be signed in to change notification settings - Fork 370
/
Copy pathutils.ts
247 lines (214 loc) · 7.24 KB
/
utils.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
import fetch from 'unfetch';
import {
DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,
CLEANUP_IFRAME_TIMEOUT_IN_SECONDS
} from './constants';
const dedupe = arr => arr.filter((x, i) => arr.indexOf(x) === i);
const TIMEOUT_ERROR = { error: 'timeout', error_description: 'Timeout' };
export const getUniqueScopes = (...scopes: string[]) => {
const scopeString = scopes.filter(Boolean).join();
return dedupe(scopeString.replace(/\s/g, ',').split(','))
.join(' ')
.trim();
};
export const parseQueryResult = (queryString: string) => {
if (queryString.indexOf('#') > -1) {
queryString = queryString.substr(0, queryString.indexOf('#'));
}
let queryParams = queryString.split('&');
let parsedQuery: any = {};
queryParams.forEach(qp => {
let [key, val] = qp.split('=');
parsedQuery[key] = decodeURIComponent(val);
});
return <AuthenticationResult>{
...parsedQuery,
expires_in: parseInt(parsedQuery.expires_in)
};
};
export const runIframe = (
authorizeUrl: string,
eventOrigin: string,
timeoutInSeconds: number = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS
) => {
return new Promise<AuthenticationResult>((res, rej) => {
var iframe = window.document.createElement('iframe');
iframe.setAttribute('width', '0');
iframe.setAttribute('height', '0');
iframe.style.display = 'none';
const timeoutSetTimeoutId = setTimeout(() => {
rej(TIMEOUT_ERROR);
window.document.body.removeChild(iframe);
}, timeoutInSeconds * 1000);
const iframeEventHandler = function(e: MessageEvent) {
if (e.origin != eventOrigin) return;
if (!e.data || e.data.type !== 'authorization_response') return;
(<any>e.source).close();
e.data.response.error ? rej(e.data.response) : res(e.data.response);
clearTimeout(timeoutSetTimeoutId);
window.removeEventListener('message', iframeEventHandler, false);
// Delay the removal of the iframe to prevent hanging loading status
// in Chrome: https://github.com/auth0/auth0-spa-js/issues/240
setTimeout(
() => window.document.body.removeChild(iframe),
CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1000
);
};
window.addEventListener('message', iframeEventHandler, false);
window.document.body.appendChild(iframe);
iframe.setAttribute('src', authorizeUrl);
});
};
const openPopup = url => {
const width = 400;
const height = 600;
const left = window.screenX + (window.innerWidth - width) / 2;
const top = window.screenY + (window.innerHeight - height) / 2;
return window.open(
url,
'auth0:authorize:popup',
`left=${left},top=${top},width=${width},height=${height},resizable,scrollbars=yes,status=1`
);
};
export const runPopup = (authorizeUrl: string, config: PopupConfigOptions) => {
let popup = config.popup;
if (popup) {
popup.location.href = authorizeUrl;
} else {
popup = openPopup(authorizeUrl);
}
if (!popup) {
throw new Error('Could not open popup');
}
return new Promise<AuthenticationResult>((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject({ ...TIMEOUT_ERROR, popup });
}, (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1000);
window.addEventListener('message', e => {
if (!e.data || e.data.type !== 'authorization_response') {
return;
}
clearTimeout(timeoutId);
popup.close();
if (e.data.response.error) {
return reject(e.data.response);
}
resolve(e.data.response);
});
});
};
export const createRandomString = () => {
const charset =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.';
let random = '';
const randomValues = Array.from(
getCrypto().getRandomValues(new Uint8Array(43))
);
randomValues.forEach(v => (random += charset[v % charset.length]));
return random;
};
export const encodeState = (state: string) => btoa(state);
export const decodeState = (state: string) => atob(state);
export const createQueryParams = (params: any) => {
return Object.keys(params)
.filter(k => typeof params[k] !== 'undefined')
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
.join('&');
};
export const sha256 = async (s: string) => {
const digestOp = getCryptoSubtle().digest(
{ name: 'SHA-256' },
new TextEncoder().encode(s)
);
// msCrypto (IE11) uses the old spec, which is not Promise based
// https://msdn.microsoft.com/en-us/expression/dn904640(v=vs.71)
// Instead of returning a promise, it returns a CryptoOperation
// with a result property in it.
// As a result, the various events need to be handled in the event that we're
// working in IE11 (hence the msCrypto check). These events just call resolve
// or reject depending on their intention.
if ((<any>window).msCrypto) {
return new Promise((res, rej) => {
digestOp.oncomplete = e => {
res(e.target.result);
};
digestOp.onerror = (e: ErrorEvent) => {
rej(e.error);
};
digestOp.onabort = () => {
rej('The digest operation was aborted');
};
});
}
return await digestOp;
};
const urlEncodeB64 = (input: string) => {
const b64Chars = { '+': '-', '/': '_', '=': '' };
return input.replace(/[\+\/=]/g, (m: string) => b64Chars[m]);
};
// https://stackoverflow.com/questions/30106476/
const decodeB64 = input =>
decodeURIComponent(
atob(input)
.split('')
.map(c => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
})
.join('')
);
export const urlDecodeB64 = (input: string) =>
decodeB64(input.replace(/_/g, '/').replace(/-/g, '+'));
export const bufferToBase64UrlEncoded = input => {
const ie11SafeInput = new Uint8Array(input);
return urlEncodeB64(
window.btoa(String.fromCharCode(...Array.from(ie11SafeInput)))
);
};
const getJSON = async (url, options) => {
const response = await fetch(url, options);
const { error, error_description, ...success } = await response.json();
if (!response.ok) {
const errorMessage =
error_description || `HTTP error. Unable to fetch ${url}`;
const e = <any>new Error(errorMessage);
e.error = error || 'request_error';
e.error_description = errorMessage;
throw e;
}
return success;
};
export const oauthToken = async ({ baseUrl, ...options }: OAuthTokenOptions) =>
await getJSON(`${baseUrl}/oauth/token`, {
method: 'POST',
body: JSON.stringify({
grant_type: 'authorization_code',
redirect_uri: window.location.origin,
...options
}),
headers: {
'Content-type': 'application/json'
}
});
export const getCrypto = () => {
//ie 11.x uses msCrypto
return <Crypto>(window.crypto || (<any>window).msCrypto);
};
export const getCryptoSubtle = () => {
const crypto = getCrypto();
//safari 10.x uses webkitSubtle
return crypto.subtle || (<any>crypto).webkitSubtle;
};
export const validateCrypto = () => {
if (!getCrypto()) {
throw new Error(
'For security reasons, `window.crypto` is required to run `auth0-spa-js`.'
);
}
if (typeof getCryptoSubtle() === 'undefined') {
throw new Error(`
auth0-spa-js must run on a secure origin.
See https://github.com/auth0/auth0-spa-js/blob/master/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin
for more information.
`);
}
};