@authorizerdev/authorizer-js 1.2.1 → 1.2.2-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils.ts DELETED
@@ -1,155 +0,0 @@
1
- import {
2
- CLEANUP_IFRAME_TIMEOUT_IN_SECONDS,
3
- DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,
4
- } from './constants'
5
- import { AuthorizeResponse } from './types'
6
-
7
- export const hasWindow = (): boolean => typeof window !== 'undefined'
8
-
9
- export const trimURL = (url: string): string => {
10
- let trimmedData = url.trim()
11
- const lastChar = trimmedData[trimmedData.length - 1]
12
- if (lastChar === '/')
13
- trimmedData = trimmedData.slice(0, -1)
14
-
15
- return trimmedData
16
- }
17
-
18
- export const getCrypto = () => {
19
- // ie 11.x uses msCrypto
20
- return hasWindow()
21
- ? ((window.crypto || (window as any).msCrypto) as Crypto)
22
- : null
23
- }
24
-
25
- export const getCryptoSubtle = () => {
26
- const crypto = getCrypto()
27
- // safari 10.x uses webkitSubtle
28
- return (crypto && crypto.subtle) || (crypto as any).webkitSubtle
29
- }
30
-
31
- export const createRandomString = () => {
32
- const charset
33
- = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.'
34
- let random = ''
35
- const crypto = getCrypto()
36
- if (crypto) {
37
- const randomValues = Array.from(crypto.getRandomValues(new Uint8Array(43)))
38
- randomValues.forEach(v => (random += charset[v % charset.length]))
39
- }
40
- return random
41
- }
42
-
43
- export const encode = (value: string) =>
44
- hasWindow() ? btoa(value) : Buffer.from(value).toString('base64')
45
- export const decode = (value: string) =>
46
- hasWindow() ? atob(value) : Buffer.from(value, 'base64').toString('ascii')
47
-
48
- export const createQueryParams = (params: any) => {
49
- return Object.keys(params)
50
- .filter(k => typeof params[k] !== 'undefined')
51
- .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
52
- .join('&')
53
- }
54
-
55
- export const sha256 = async (s: string) => {
56
- const digestOp: any = getCryptoSubtle().digest(
57
- { name: 'SHA-256' },
58
- new TextEncoder().encode(s),
59
- )
60
-
61
- // msCrypto (IE11) uses the old spec, which is not Promise based
62
- // https://msdn.microsoft.com/en-us/expression/dn904640(v=vs.71)
63
- if ((window as any).msCrypto) {
64
- return new Promise((resolve, reject) => {
65
- digestOp.oncomplete = (e: any) => {
66
- resolve(e.target.result)
67
- }
68
-
69
- digestOp.onerror = (e: ErrorEvent) => {
70
- reject(e.error)
71
- }
72
-
73
- digestOp.onabort = () => {
74
- reject(new Error('The digest operation was aborted'))
75
- }
76
- })
77
- }
78
-
79
- return await digestOp
80
- }
81
-
82
- const urlEncodeB64 = (input: string) => {
83
- const b64Chars: { [index: string]: string } = { '+': '-', '/': '_', '=': '' }
84
- return input.replace(/[+/=]/g, (m: string) => b64Chars[m])
85
- }
86
-
87
- // https://stackoverflow.com/questions/30106476/
88
- const decodeB64 = (input: string) =>
89
- decodeURIComponent(
90
- atob(input)
91
- .split('')
92
- .map((c) => {
93
- return `%${(`00${c.charCodeAt(0).toString(16)}`).slice(-2)}`
94
- })
95
- .join(''),
96
- )
97
-
98
- export const urlDecodeB64 = (input: string) =>
99
- decodeB64(input.replace(/_/g, '/').replace(/-/g, '+'))
100
-
101
- export const bufferToBase64UrlEncoded = (input: number[] | Uint8Array) => {
102
- const ie11SafeInput = new Uint8Array(input)
103
- return urlEncodeB64(
104
- window.btoa(String.fromCharCode(...Array.from(ie11SafeInput))),
105
- )
106
- }
107
-
108
- export const executeIframe = (
109
- authorizeUrl: string,
110
- eventOrigin: string,
111
- timeoutInSeconds: number = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,
112
- ) => {
113
- return new Promise<AuthorizeResponse>((resolve, reject) => {
114
- const iframe = window.document.createElement('iframe')
115
- iframe.setAttribute('id', 'authorizer-iframe')
116
- iframe.setAttribute('width', '0')
117
- iframe.setAttribute('height', '0')
118
- iframe.style.display = 'none'
119
-
120
- let iframeEventHandler: (e: MessageEvent) => void
121
-
122
- const removeIframe = () => {
123
- if (window.document.body.contains(iframe)) {
124
- window.document.body.removeChild(iframe)
125
- window.removeEventListener('message', iframeEventHandler, false)
126
- }
127
- }
128
-
129
- const timeoutSetTimeoutId = setTimeout(() => {
130
- removeIframe()
131
- }, timeoutInSeconds * 1000)
132
-
133
- iframeEventHandler = function (e: MessageEvent) {
134
- if (e.origin !== eventOrigin)
135
- return
136
- if (!e.data || !e.data.response)
137
- return
138
-
139
- const eventSource = e.source
140
-
141
- if (eventSource)
142
- (eventSource as any).close()
143
-
144
- e.data.response.error ? reject(e.data.response) : resolve(e.data.response)
145
-
146
- clearTimeout(timeoutSetTimeoutId)
147
- window.removeEventListener('message', iframeEventHandler, false)
148
- setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1000)
149
- }
150
-
151
- window.addEventListener('message', iframeEventHandler, false)
152
- window.document.body.appendChild(iframe)
153
- iframe.setAttribute('src', authorizeUrl)
154
- })
155
- }