-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathreact-native-worker.ts
More file actions
277 lines (250 loc) · 7.54 KB
/
Copy pathreact-native-worker.ts
File metadata and controls
277 lines (250 loc) · 7.54 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import hashjs from 'hash.js'
import HmacDRBG from 'hmac-drbg'
import { base64 } from 'rfc4648'
import { makeFetchResponse } from 'serverlet'
import { Bridge, bridgifyObject } from 'yaob'
import {
addEdgeCorePlugins,
lockEdgeCorePlugins,
makeContext,
makeFakeWorld
} from '../../core/core'
import { LogBackend, makeLog } from '../../core/log/log'
import {
EdgeFetchFunction,
EdgeFetchOptions,
EdgeFetchResponse,
EdgeIo
} from '../../types/types'
import { queueMixFetch } from '../../util/nym'
import { hideProperties } from '../hidden-properties'
import { makeNativeBridge } from './native-bridge'
import { WorkerApi, YAOB_THROTTLE_MS } from './react-native-types'
// Tracks the status of different URI endpoints for the CORS bouncer:
const endpointCorsState = new Map<
string,
{
// The window.fetch worked:
windowSuccess: boolean
// The nativeFetch worked:
nativeSuccess: boolean
}
>()
// Set up the bridges:
const [nativeBridge, reactBridge] =
window.edgeCore != null
? [
// Android:
makeNativeBridge((id, name, args) => {
window.edgeCore.call(id, name, JSON.stringify(args))
}),
new Bridge({
hideProperties,
sendMessage(message) {
window.edgeCore.postMessage(JSON.stringify(message))
},
throttleMs: YAOB_THROTTLE_MS
})
]
: [
// iOS:
makeNativeBridge((id, name, args) => {
window.webkit.messageHandlers.edgeCore.postMessage([id, name, args])
}),
new Bridge({
hideProperties,
sendMessage(message) {
window.webkit.messageHandlers.edgeCore.postMessage([
0,
'postMessage',
[JSON.stringify(message)]
])
},
throttleMs: YAOB_THROTTLE_MS
})
]
// Set up global objects:
window.addEdgeCorePlugins = addEdgeCorePlugins
window.nativeBridge = nativeBridge
window.reactBridge = reactBridge
function loadPlugins(pluginUris: string[]): void {
const { head } = window.document
if (head == null || pluginUris.length === 0) {
lockEdgeCorePlugins()
return
}
let loaded: number = 0
const handleLoad = (): void => {
if (++loaded >= pluginUris.length) lockEdgeCorePlugins()
}
for (const uri of pluginUris) {
const script = document.createElement('script')
script.addEventListener('error', handleLoad)
script.addEventListener('load', handleLoad)
script.charset = 'utf-8'
script.defer = true
script.src = uri
head.appendChild(script)
}
}
async function makeIo(logBackend: LogBackend): Promise<EdgeIo> {
const log = makeLog(logBackend, 'react-native-io')
const csprng = new HmacDRBG({
hash: hashjs.sha256,
entropy: base64.parse(await nativeBridge.call('randomBytes', 32))
})
const nativeFetch: EdgeFetchFunction = async (uri, opts = {}) => {
const { method = 'GET', headers = {}, body } = opts
const response = await nativeBridge.call(
'fetch',
uri,
method,
headers,
body instanceof ArrayBuffer
? base64.stringify(new Uint8Array(body))
: body,
body instanceof ArrayBuffer
)
return makeFetchResponse({
status: response.status,
headers: response.headers,
body: response.bodyIsBase64 ? base64.parse(response.body) : response.body
})
}
const io: EdgeIo = {
disklet: {
delete(path) {
return nativeBridge.call('diskletDelete', normalizePath(path))
},
async getData(path) {
const data: string = await nativeBridge.call(
'diskletGetData',
normalizePath(path)
)
return base64.parse(data)
},
getText(path) {
return nativeBridge.call('diskletGetText', normalizePath(path))
},
list(path = '') {
return nativeBridge.call('diskletList', normalizePath(path))
},
setData(path, data: any) {
return nativeBridge.call(
'diskletSetData',
normalizePath(path),
base64.stringify(data)
)
},
setText(path, text) {
return nativeBridge.call('diskletSetText', normalizePath(path), text)
}
},
random: bytes => csprng.generate(bytes),
async scrypt(data, salt, n, r, p, dklen) {
const hash: string = await nativeBridge.call(
'scrypt',
base64.stringify(data),
base64.stringify(salt),
n,
r,
p,
dklen
)
return base64.parse(hash)
},
// Networking:
async fetch(
uri: string,
opts?: EdgeFetchOptions
): Promise<EdgeFetchResponse> {
const { corsBypass = 'auto', privacy = 'none' } = opts ?? {}
if (privacy === 'nym') {
// Use queued fetch to handle mixFetch's one-request-per-host limitation
// initMixFetch is called within queueMixFetch
const response = await queueMixFetch(
uri,
{
...opts,
mode: 'unsafe-ignore-cors' as RequestMode
},
log
)
return response
}
if (corsBypass === 'always') {
return await nativeFetch(uri, opts)
}
if (corsBypass === 'never') {
return await window.fetch(uri, opts)
}
const { protocol, host, pathname } = new URL(uri)
const endpoint = `${protocol}//${host}${pathname}`
const state = endpointCorsState.get(endpoint) ?? {
windowSuccess: false,
nativeSuccess: false
}
if (!endpointCorsState.has(endpoint)) {
endpointCorsState.set(endpoint, state)
}
// If the native fetch worked,
// then we can guess that the server has a CORS problem,
// so don't even bother with `window.fetch`:
if (!state.nativeSuccess) {
try {
const response = await window.fetch(uri, opts)
state.windowSuccess = true
return response
} catch (error: unknown) {
// If `window.fetch` has ever worked,
// then we know the server has the right CORS headers,
// so don't even bother with the native fallback:
if (state.windowSuccess) throw error
}
}
const response = await nativeFetch(uri, opts)
state.nativeSuccess = true
return response
},
async fetchCors(
uri: string,
opts: EdgeFetchOptions = {}
): Promise<EdgeFetchResponse> {
return await io.fetch(uri, opts)
}
}
return io
}
/**
* Interprets a path as a series of folder lookups,
* handling special components like `.` and `..`.
*/
export function normalizePath(path: string): string {
if (/^\//.test(path)) throw new Error('Absolute paths are not supported')
const parts = path.split('/')
// Shift down good elements, dropping bad ones:
let i = 0 // Read index
let j = 0 // Write index
while (i < parts.length) {
const part = parts[i++]
if (part === '..') j--
else if (part !== '.' && part !== '') parts[j++] = part
if (j < 0) throw new Error('Path would escape folder')
}
// Array items from 0 to j are the path:
return parts.slice(0, j).join('/')
}
// Send the root object:
const workerApi: WorkerApi = bridgifyObject({
async makeEdgeContext(nativeIo, logBackend, pluginUris, opts) {
loadPlugins(pluginUris)
const io = await makeIo(logBackend)
return await makeContext({ io, nativeIo }, logBackend, opts)
},
async makeFakeEdgeWorld(nativeIo, logBackend, pluginUris, users = []) {
loadPlugins(pluginUris)
const io = await makeIo(logBackend)
return makeFakeWorld({ io, nativeIo }, logBackend, users)
}
})
reactBridge.sendRoot(workerApi)