-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
280 lines (217 loc) · 6.81 KB
/
index.js
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
278
279
280
import omnistreams from './lib/omnistreams-js/index.js';
import { Server as HttpServer, directoryTreeHandler } from './lib/http-js/index.js';
import { openDirectory } from './lib/fs-js/index.js';
//import { getToken } from './lib/oauth2-js/index.js';
const MESSAGE_TYPE_TUNNEL_CONFIG = 0;
const MESSAGE_TYPE_SUCCESS = 1;
const MESSAGE_TYPE_ERROR = 2;
const MESSAGE_TYPE_STREAM = 3;
let serverUri = `https://waygate.io`;
function setServerUri(uri) {
serverUri = uri;
}
function wrapWebTransportStream(stream, firstMessage) {
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();
// TODO: this feels like a race condition
(async () => {
await writer.write(firstMessage);
writer.releaseLock();
})();
return {
readable,
writable: stream.writable,
}
}
async function wrapWebTransport(wtConn) {
await wtConn.ready;
const { readable, writable } = new TransformStream();
//const streamReader = readable.getReader();
const streamWriter = writable.getWriter();
const incomingStreamsReader = wtConn.incomingBidirectionalStreams.getReader();
let onTunConfig;
const tunConfigPromise = new Promise((resolve, reject) => {
onTunConfig = resolve;
});
(async () => {
//for await (const stream of wtConn.incomingBidirectionalStreams) {
while (true) {
const incomingStream = await incomingStreamsReader.read();
const stream = incomingStream.value;
const reader = stream.readable.getReader();
const { value, done } = await reader.read();
reader.releaseLock();
const msg = value;
const msgType = msg[0];
switch (msgType) {
case MESSAGE_TYPE_TUNNEL_CONFIG: {
const tunConfig = JSON.parse(new TextDecoder().decode(msg.slice(1)));
onTunConfig(tunConfig);
const writer = stream.writable.getWriter();
await writer.write(new Uint8Array([MESSAGE_TYPE_SUCCESS]));
// TODO: this is a hack. When using WebTransport, it was closing the
// stream before the reponse code got received by the server. Need
// to figure out a way to close while guaranteeing any previous
// writes have been received.
//(async() => {
// await sleep(1000);
// writer.close()
//})();
await writer.close()
break;
}
case MESSAGE_TYPE_STREAM: {
await streamWriter.write(wrapWebTransportStream(stream, msg.slice(1)));
break;
}
default: {
throw new Error("Unknown message type: " + msgType);
}
}
if (incomingStream.done) {
break;
}
}
})();
const tunConfig = await tunConfigPromise;
return {
connectionStream: readable,
getDomain() {
return tunConfig.domain;
}
};
}
async function listen(options) {
let tunnelType = 'webtransport';
let token = "";
if (options) {
if (options.tunnelType) {
tunnelType = options.tunnelType;
if (tunnelType !== 'webtransport' && tunnelType !== 'websocket') {
throw new Error("Unknown tunnel type: " + tunnelType);
}
if (tunnelType === 'webtransport' && !webtransportSupported()) {
throw new Error("WebTransport not supported by your JavaScript runtime");
}
}
if (options.token) {
token = options.token;
}
}
let WebTransportType = omnistreams.WebTransport;
if (webtransportSupported() && tunnelType !== 'websocket') {
WebTransportType = WebTransport;
}
const conn = new WebTransportType(`${serverUri}/waygate?token=${token}&termination-type=server`);
return wrapWebTransport(conn);
}
async function serve(listener, handler) {
const httpServer = new HttpServer();
return httpServer.serve(listener, handler);
}
function webtransportSupported() {
return 'WebTransport' in globalThis;
}
async function startTokenFlow() {
const clientId = window.location.origin;
const redirectUri = window.location.href;
const state = genRandomText(32);
const pkceVerifier = genRandomText(32);
const pkceChallenge = await generateCodeChallengeFromVerifier(pkceVerifier);
const authUri = `${serverUri}/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&state=${state}&response_type=code&scope=waygate&code_challenge_method=S256&code_challenge=${pkceChallenge}`;
const authRequest = {
serverUri,
clientId,
redirectUri,
pkceVerifier,
};
localStorage.setItem(state, JSON.stringify(authRequest));
window.location.href = authUri;
}
async function checkTokenFlow() {
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const state = params.get('state');
if (!code || !state) {
return;
}
const authRequestJson = localStorage.getItem(state);
if (!authRequestJson) {
throw new Error("No such auth request");
}
const authRequest = JSON.parse(authRequestJson);
const res = await fetch(authRequest.serverUri + "/oauth2/token", {
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
code,
client_id: authRequest.clientId,
redirect_uri: authRequest.redirectUri,
grant_type: 'authorization_code',
code_verifier: authRequest.pkceVerifier,
}),
});
const json = await res.json();
localStorage.setItem('waygate_token', json.access_token);
localStorage.removeItem(state);
window.history.pushState({}, '', authRequest.redirectUri);
}
async function getToken() {
await checkTokenFlow();
const token = localStorage.getItem('waygate_token');
if (!token) {
await startTokenFlow();
}
return token;
}
function genRandomText(len) {
const possible = "0123456789abcdefghijkmnpqrstuvwxyz";
let text = "";
for (let i = 0; i < len; i++) {
const randIndex = Math.floor(Math.random() * possible.length);
text += possible[randIndex];
}
return text;
}
// Taken from https://stackoverflow.com/a/63336562/943814
function sha256(plain) {
// returns promise ArrayBuffer
const encoder = new TextEncoder();
const data = encoder.encode(plain);
return window.crypto.subtle.digest("SHA-256", data);
}
function base64urlencode(a) {
var str = "";
var bytes = new Uint8Array(a);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
str += String.fromCharCode(bytes[i]);
}
return btoa(str)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
}
async function generateCodeChallengeFromVerifier(v) {
var hashed = await sha256(v);
var base64encoded = base64urlencode(hashed);
return base64encoded;
}
async function sleep(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
}
export {
setServerUri,
getToken,
checkTokenFlow,
startTokenFlow,
listen,
serve,
HttpServer,
openDirectory,
directoryTreeHandler,
};