webvm/tun/tailscale_tun.js

108 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-09-19 07:41:14 +00:00
import "./wasm_exec.js";
import ipStackAwait from "./ipstack.js";
export const State = {
NoState: 0,
InUseOtherUser: 1,
NeedsLogin: 2,
NeedsMachineAuth: 3,
Stopped: 4,
Starting: 5,
Running: 6,
};
export async function init() {
2022-09-19 07:41:14 +00:00
const {IpStack} = await ipStackAwait();
IpStack.init();
2022-09-19 07:41:14 +00:00
const listeners = {
onstateupdate: () => {},
onnetmap: () => {},
onloginurl: () => {},
}
2022-09-19 07:41:14 +00:00
let ipn = null;
let localIp = null;
let dnsIp = null;
2022-09-19 07:41:14 +00:00
const lazyRunIpn = async () => {
const wasmUrl = new URL("tailscale.wasm", import.meta.url);
const go = new window.Go();
let {instance} = await fetch(wasmUrl).then(x => x.arrayBuffer()).then(x => WebAssembly.instantiate(x,go.importObject));
go.run(instance);
const sessionStateStorage = {
setState(id, value) {
window.sessionStorage[`ipn-state-${id}`] = value
},
getState(id) {
return window.sessionStorage[`ipn-state-${id}`] || ""
},
}
ipn = newIPN({
// Persist IPN state in sessionStorage in development, so that we don't need
// to re-authorize every time we reload the page.
2022-09-30 18:45:50 +00:00
//stateStorage: sessionStateStorage,
});
2022-09-19 07:41:14 +00:00
const setupIpStack = () => {
ipn.tun.onmessage = function(ev) {
IpStack.input(ev.data)
};
IpStack.output(function(p){
2022-12-14 15:37:04 +00:00
ipn.tun.postMessage(p, [p.buffer]);
});
2022-09-19 07:41:14 +00:00
};
setupIpStack();
ipn.run({
notifyState: (s) => listeners.onstateupdate(s),
notifyNetMap: (s) => {
const netMap = JSON.parse(s);
listeners.onnetmap(netMap);
const newLocalIp = netMap.self.addresses[0];
if (localIp != newLocalIp)
{
localIp = newLocalIp;
2022-12-14 15:37:04 +00:00
try{
IpStack.up({localIp, dnsIp, ipMap: {
["127.0.0.53"]: dnsIp,
[dnsIp]: "127.0.0.53",
}});
2022-12-14 15:37:04 +00:00
}catch(e){
console.log(e);
debugger;
}
}
},
notifyBrowseToURL: (l) => listeners.onloginurl(l),
2022-09-19 07:41:14 +00:00
});
};
2022-09-19 07:41:14 +00:00
return {
tcpSocket: IpStack.TCPSocket.create,
udpSocket: IpStack.UDPSocket.create,
2022-09-19 07:41:14 +00:00
parseIP: IpStack.parseIP,
2022-12-14 15:37:04 +00:00
resolve: IpStack.resolve,
up: async (conf) => {
if (ipn == null) {
await lazyRunIpn();
}
2022-09-19 07:41:14 +00:00
ipn.up(conf);
localIp = null;
dnsIp = conf.dnsIp || "127.0.0.53";
},
down: () => {
ipn.down();
IpStack.down();
},
login: () => ipn.login(),
logout: () => ipn.logout(),
listeners
2022-09-19 07:41:14 +00:00
};
}