@glassly/miniapp-cli 0.1.17-dev.2 → 0.1.18-dev.0
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/package.json +2 -1
- package/src/dev-tunnel.test.ts +9 -0
- package/src/dev-tunnel.ts +23 -96
- package/src/iroh-tunnel.ts +276 -0
- package/src/link/command.ts +102 -0
- package/src/link/daemon.ts +338 -0
- package/src/link/link.test.ts +357 -0
- package/src/link/state.ts +113 -0
- package/src/link/upgrade.ts +66 -0
- package/src/sim/types/index.ts +9 -1
- package/src/sim/types/link.ts +45 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glassly/miniapp-cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.18-dev.0",
|
|
4
4
|
"description": "Build tooling for Glassly miniapps: dev server, packer, manifest validation, and JSON Schema. The `glassly` command that drives it ships in @glassly/cli.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
".": "./src/api.ts",
|
|
12
12
|
"./build-helpers": "./src/build-helpers.ts",
|
|
13
13
|
"./lan": "./src/lan.ts",
|
|
14
|
+
"./link": "./src/link/command.ts",
|
|
14
15
|
"./package.json": "./package.json"
|
|
15
16
|
},
|
|
16
17
|
"scripts": {
|
package/src/dev-tunnel.test.ts
CHANGED
|
@@ -95,6 +95,15 @@ describe('startDevTunnel', () => {
|
|
|
95
95
|
expect(response).toBe('');
|
|
96
96
|
}, 20_000);
|
|
97
97
|
|
|
98
|
+
test('resets a stream whose header never finishes', async () => {
|
|
99
|
+
const conn = await client.connect(EndpointTicket.fromString(tunnel.ticket()).endpointAddr(), ALPN);
|
|
100
|
+
const bi = await conn.openBi();
|
|
101
|
+
await bi.send.writeAll([TARGET_HTTP]);
|
|
102
|
+
const startedAt = Date.now();
|
|
103
|
+
await expect(bi.recv.read(1024)).rejects.toThrow();
|
|
104
|
+
expect(Date.now() - startedAt).toBeLessThan(10_000);
|
|
105
|
+
}, 20_000);
|
|
106
|
+
|
|
98
107
|
test('keeps the endpoint id across restarts', async () => {
|
|
99
108
|
const again = await startDevTunnel({packageName: 'com.example.tunnel', httpPort: http.port!, devPort: null, identityDir: dir, log: () => {}});
|
|
100
109
|
try {
|
package/src/dev-tunnel.ts
CHANGED
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
import {randomBytes, timingSafeEqual} from 'crypto';
|
|
2
|
-
import {once} from 'events';
|
|
3
2
|
import {chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync} from 'fs';
|
|
4
|
-
import net from 'net';
|
|
5
3
|
import os from 'os';
|
|
6
4
|
import {join} from 'path';
|
|
7
|
-
import type {BiStream, Connection, Endpoint
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
5
|
+
import type {BiStream, Connection, Endpoint} from '@number0/iroh';
|
|
6
|
+
import {
|
|
7
|
+
acceptConnections,
|
|
8
|
+
acceptStreams,
|
|
9
|
+
bindEndpoint,
|
|
10
|
+
connectTcp,
|
|
11
|
+
describePath,
|
|
12
|
+
loadIroh,
|
|
13
|
+
readHeader,
|
|
14
|
+
refuse,
|
|
15
|
+
splice,
|
|
16
|
+
TUNNEL_ALPN,
|
|
17
|
+
} from './iroh-tunnel.js';
|
|
18
|
+
|
|
19
|
+
export const DEV_TUNNEL_ALPN = TUNNEL_ALPN;
|
|
12
20
|
export const TARGET_HTTP = 0;
|
|
13
21
|
export const TARGET_DEV = 1;
|
|
14
22
|
|
|
15
|
-
const ONLINE_TIMEOUT_MS = 5_000;
|
|
16
|
-
const READ_CHUNK_BYTES = 64 * 1024;
|
|
17
|
-
|
|
18
23
|
export interface DevTunnelIdentity {
|
|
19
24
|
secretKey: string;
|
|
20
25
|
token: string;
|
|
@@ -72,64 +77,14 @@ export function tokenMatches(presented: number[], expected: string): boolean {
|
|
|
72
77
|
return got.length === want.length && timingSafeEqual(got, want);
|
|
73
78
|
}
|
|
74
79
|
|
|
75
|
-
type Iroh = typeof import('@number0/iroh');
|
|
76
|
-
|
|
77
|
-
async function loadIroh(): Promise<Iroh | string> {
|
|
78
|
-
try {
|
|
79
|
-
return await import('@number0/iroh');
|
|
80
|
-
} catch (error) {
|
|
81
|
-
return `no iroh binding for ${process.platform}-${process.arch} (${(error as Error).message.split('\n')[0]})`;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function describePath(conn: Connection): string {
|
|
86
|
-
const selected = conn.paths().find((p) => p.isSelected);
|
|
87
|
-
if (!selected) return 'connecting';
|
|
88
|
-
const rtt = typeof selected.rttMs === 'number' ? `, ${Math.round(selected.rttMs)} ms` : '';
|
|
89
|
-
return `${selected.isRelay ? 'relay' : 'direct'}${rtt}`;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
async function pumpToSocket(recv: RecvStream, socket: net.Socket): Promise<void> {
|
|
93
|
-
try {
|
|
94
|
-
for (;;) {
|
|
95
|
-
const chunk = await recv.read(READ_CHUNK_BYTES);
|
|
96
|
-
if (chunk.length === 0) break;
|
|
97
|
-
if (!socket.write(Buffer.from(chunk))) await once(socket, 'drain');
|
|
98
|
-
}
|
|
99
|
-
socket.end();
|
|
100
|
-
} catch {
|
|
101
|
-
socket.destroy();
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
async function pumpToStream(socket: net.Socket, send: SendStream): Promise<void> {
|
|
106
|
-
try {
|
|
107
|
-
for await (const chunk of socket) {
|
|
108
|
-
await send.writeAll(Array.from(chunk as Buffer));
|
|
109
|
-
}
|
|
110
|
-
await send.finish();
|
|
111
|
-
} catch {
|
|
112
|
-
await send.reset(0n).catch(() => {});
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
80
|
async function handleStream(bi: BiStream, token: string, ports: Record<number, number | null>): Promise<void> {
|
|
117
|
-
const {send, recv} = bi;
|
|
118
81
|
try {
|
|
119
|
-
const
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
await send.reset(1n);
|
|
124
|
-
await recv.stop(1n);
|
|
125
|
-
return;
|
|
126
|
-
}
|
|
127
|
-
const socket = net.connect({host: '127.0.0.1', port});
|
|
128
|
-
await once(socket, 'connect');
|
|
129
|
-
socket.setNoDelay(true);
|
|
130
|
-
await Promise.all([pumpToSocket(recv, socket), pumpToStream(socket, send)]);
|
|
82
|
+
const header = await readHeader(bi.recv);
|
|
83
|
+
const port = header && ports[header.target];
|
|
84
|
+
if (!header || !tokenMatches(Array.from(header.token), token) || !port) return refuse(bi);
|
|
85
|
+
await splice(bi, await connectTcp('127.0.0.1', port));
|
|
131
86
|
} catch {
|
|
132
|
-
await send.reset(0n).catch(() => {});
|
|
87
|
+
await bi.send.reset(0n).catch(() => {});
|
|
133
88
|
}
|
|
134
89
|
}
|
|
135
90
|
|
|
@@ -146,30 +101,7 @@ async function handleConnection(conn: Connection, token: string, ports: Record<n
|
|
|
146
101
|
if (left > 0) liveConnections.set(remote, left);
|
|
147
102
|
else liveConnections.delete(remote);
|
|
148
103
|
});
|
|
149
|
-
|
|
150
|
-
let bi: BiStream;
|
|
151
|
-
try {
|
|
152
|
-
bi = await conn.acceptBi();
|
|
153
|
-
} catch {
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
156
|
-
void handleStream(bi, token, ports);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
async function acceptLoop(endpoint: Endpoint, token: string, ports: Record<number, number | null>, log: (line: string) => void) {
|
|
161
|
-
for (;;) {
|
|
162
|
-
const incoming = await endpoint.acceptNext().catch(() => null);
|
|
163
|
-
if (!incoming) return;
|
|
164
|
-
void (async () => {
|
|
165
|
-
try {
|
|
166
|
-
const conn = await (await incoming.accept()).connect();
|
|
167
|
-
await handleConnection(conn, token, ports, log);
|
|
168
|
-
} catch {
|
|
169
|
-
// handshake failed or the phone went away mid-connect
|
|
170
|
-
}
|
|
171
|
-
})();
|
|
172
|
-
}
|
|
104
|
+
await acceptStreams(conn, bi => handleStream(bi, token, ports));
|
|
173
105
|
}
|
|
174
106
|
|
|
175
107
|
/**
|
|
@@ -190,19 +122,14 @@ export async function startDevTunnel(options: DevTunnelOptions): Promise<DevTunn
|
|
|
190
122
|
);
|
|
191
123
|
let endpoint: Endpoint;
|
|
192
124
|
try {
|
|
193
|
-
endpoint = await iroh.
|
|
194
|
-
secretKey: Array.from(Buffer.from(identity.secretKey, 'hex')),
|
|
195
|
-
alpns: [Array.from(Buffer.from(DEV_TUNNEL_ALPN))],
|
|
196
|
-
});
|
|
125
|
+
endpoint = await bindEndpoint(iroh, Array.from(Buffer.from(identity.secretKey, 'hex')));
|
|
197
126
|
} catch (error) {
|
|
198
127
|
log(`iroh tunnel disabled: ${(error as Error).message}. The QR only carries the LAN URL.`);
|
|
199
128
|
return null;
|
|
200
129
|
}
|
|
201
|
-
// The relay URL only lands in the ticket once the endpoint has a home relay.
|
|
202
|
-
await Promise.race([endpoint.online(), new Promise((resolve) => setTimeout(resolve, ONLINE_TIMEOUT_MS))]);
|
|
203
130
|
|
|
204
131
|
const ports = {[TARGET_HTTP]: options.httpPort, [TARGET_DEV]: options.devPort};
|
|
205
|
-
void
|
|
132
|
+
void acceptConnections(endpoint, conn => handleConnection(conn, identity.token, ports, log));
|
|
206
133
|
|
|
207
134
|
return {
|
|
208
135
|
endpointId: endpoint.id().toString(),
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import {once} from 'events';
|
|
2
|
+
import net from 'net';
|
|
3
|
+
import {Duplex} from 'stream';
|
|
4
|
+
import type {BiStream, Connection, Endpoint, EndpointAddr, RecvStream, SendStream} from '@number0/iroh';
|
|
5
|
+
|
|
6
|
+
// Wire protocol shared with mobile/modules/dev-tunnel/rust/src/tunnel.rs, which the Glassly App
|
|
7
|
+
// runs: every bi-stream opens with [target, tokenLength, ...token], then carries raw TCP bytes.
|
|
8
|
+
// `glassly dev` and `glassly link` accept it; dialTunnel plays the phone's side. Only `glassly dev`
|
|
9
|
+
// trusts the header token: `glassly link` ignores it and checks a credential inside each request.
|
|
10
|
+
export const TUNNEL_ALPN = 'glassly/dev-tunnel/1';
|
|
11
|
+
const ALPN_BYTES = Array.from(Buffer.from(TUNNEL_ALPN));
|
|
12
|
+
const READ_CHUNK_BYTES = 64 * 1024;
|
|
13
|
+
const PORT_PAIR_ATTEMPTS = 20;
|
|
14
|
+
const DIAL_TIMEOUT_MS = 15_000;
|
|
15
|
+
const ONLINE_TIMEOUT_MS = 5_000;
|
|
16
|
+
const HEADER_TIMEOUT_MS = 5_000;
|
|
17
|
+
|
|
18
|
+
export type Iroh = typeof import('@number0/iroh');
|
|
19
|
+
|
|
20
|
+
export interface StreamHeader {
|
|
21
|
+
target: number;
|
|
22
|
+
token: Buffer;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface DialedTunnel {
|
|
26
|
+
endpointId: string;
|
|
27
|
+
ports: [number, number];
|
|
28
|
+
close(): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function loadIroh(): Promise<Iroh | string> {
|
|
32
|
+
try {
|
|
33
|
+
return await import('@number0/iroh');
|
|
34
|
+
} catch (error) {
|
|
35
|
+
return `no iroh binding for ${process.platform}-${process.arch} (${(error as Error).message.split('\n')[0]})`;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Waits up to 5 s for a home relay: the relay URL only lands in the ticket once there is one.
|
|
40
|
+
export async function bindEndpoint(iroh: Iroh, secretKey: number[]): Promise<Endpoint> {
|
|
41
|
+
const endpoint = await iroh.Endpoint.bind({secretKey, alpns: [ALPN_BYTES]});
|
|
42
|
+
await Promise.race([endpoint.online(), new Promise(resolve => setTimeout(resolve, ONLINE_TIMEOUT_MS))]);
|
|
43
|
+
return endpoint;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function describePath(conn: Connection): string {
|
|
47
|
+
const selected = conn.paths().find(p => p.isSelected);
|
|
48
|
+
if (!selected) return 'connecting';
|
|
49
|
+
const rtt = typeof selected.rttMs === 'number' ? `, ${Math.round(selected.rttMs)} ms` : '';
|
|
50
|
+
return `${selected.isRelay ? 'relay' : 'direct'}${rtt}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function readHeaderBytes(recv: RecvStream): Promise<StreamHeader> {
|
|
54
|
+
const [target, tokenLength] = await recv.readExact(2);
|
|
55
|
+
const token = tokenLength > 0 ? await recv.readExact(tokenLength) : [];
|
|
56
|
+
return {target, token: Buffer.from(token)};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// The Glassly App writes the header with a stream's first bytes, so null (no header within 5 s)
|
|
60
|
+
// means a peer is holding streams open, and the caller refuses the stream.
|
|
61
|
+
export async function readHeader(recv: RecvStream): Promise<StreamHeader | null> {
|
|
62
|
+
return withTimeout(readHeaderBytes(recv), HEADER_TIMEOUT_MS, 'no stream header').catch(() => null);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function refuse(bi: BiStream): Promise<void> {
|
|
66
|
+
await bi.send.reset(1n).catch(() => {});
|
|
67
|
+
await bi.recv.stop(1n).catch(() => {});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function pumpToSocket(recv: RecvStream, socket: net.Socket): Promise<void> {
|
|
71
|
+
try {
|
|
72
|
+
for (;;) {
|
|
73
|
+
const chunk = await recv.read(READ_CHUNK_BYTES);
|
|
74
|
+
if (chunk.length === 0) break;
|
|
75
|
+
if (!socket.write(Buffer.from(chunk))) await once(socket, 'drain');
|
|
76
|
+
}
|
|
77
|
+
socket.end();
|
|
78
|
+
} catch {
|
|
79
|
+
socket.destroy();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function pumpToStream(socket: net.Socket, send: SendStream): Promise<void> {
|
|
84
|
+
try {
|
|
85
|
+
for await (const chunk of socket) {
|
|
86
|
+
await send.writeAll(Array.from(chunk as Buffer));
|
|
87
|
+
}
|
|
88
|
+
await send.finish();
|
|
89
|
+
} catch {
|
|
90
|
+
await send.reset(0n).catch(() => {});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function splice(bi: BiStream, socket: net.Socket): Promise<void> {
|
|
95
|
+
socket.setNoDelay(true);
|
|
96
|
+
await Promise.all([pumpToSocket(bi.recv, socket), pumpToStream(socket, bi.send)]);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
class StreamDuplex extends Duplex {
|
|
100
|
+
private pulling = false;
|
|
101
|
+
|
|
102
|
+
constructor(private readonly bi: BiStream) {
|
|
103
|
+
super();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
setTimeout(): this {
|
|
107
|
+
return this;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
setNoDelay(): this {
|
|
111
|
+
return this;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
setKeepAlive(): this {
|
|
115
|
+
return this;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
_read(): void {
|
|
119
|
+
if (this.pulling) return;
|
|
120
|
+
this.pulling = true;
|
|
121
|
+
void this.pull();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private async pull(): Promise<void> {
|
|
125
|
+
try {
|
|
126
|
+
for (;;) {
|
|
127
|
+
const chunk = await this.bi.recv.read(READ_CHUNK_BYTES);
|
|
128
|
+
if (chunk.length === 0) {
|
|
129
|
+
this.push(null);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (!this.push(Buffer.from(chunk))) {
|
|
133
|
+
this.pulling = false;
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
} catch (error) {
|
|
138
|
+
this.destroy(error as Error);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
_write(chunk: Buffer, _encoding: BufferEncoding, done: (error?: Error | null) => void): void {
|
|
143
|
+
this.bi.send.writeAll(Array.from(chunk)).then(() => done(), done);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
_final(done: (error?: Error | null) => void): void {
|
|
147
|
+
this.bi.send.finish().then(() => done(), done);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
_destroy(error: Error | null, done: (error?: Error | null) => void): void {
|
|
151
|
+
if (!this.writableFinished) void this.bi.send.reset(0n).catch(() => {});
|
|
152
|
+
void this.bi.recv.stop(0n).catch(() => {});
|
|
153
|
+
done(error);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// A bi-stream as the socket node's http.Server takes through its 'connection' event.
|
|
158
|
+
export function streamSocket(bi: BiStream): Duplex {
|
|
159
|
+
return new StreamDuplex(bi);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export async function connectTcp(host: string, port: number): Promise<net.Socket> {
|
|
163
|
+
const socket = net.connect({host, port});
|
|
164
|
+
await once(socket, 'connect');
|
|
165
|
+
return socket;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function acceptConnections(endpoint: Endpoint, onConnection: (conn: Connection) => Promise<void>): Promise<void> {
|
|
169
|
+
for (;;) {
|
|
170
|
+
const incoming = await endpoint.acceptNext().catch(() => null);
|
|
171
|
+
if (!incoming) return;
|
|
172
|
+
void (async () => {
|
|
173
|
+
try {
|
|
174
|
+
await onConnection(await (await incoming.accept()).connect());
|
|
175
|
+
} catch {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
})();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function acceptStreams(conn: Connection, onStream: (bi: BiStream) => Promise<void>): Promise<void> {
|
|
183
|
+
for (;;) {
|
|
184
|
+
let bi: BiStream;
|
|
185
|
+
try {
|
|
186
|
+
bi = await conn.acceptBi();
|
|
187
|
+
} catch {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
void onStream(bi).catch(() => bi.send.reset(0n).catch(() => {}));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function parseAddr(iroh: Iroh, ticket: string): EndpointAddr {
|
|
195
|
+
const trimmed = ticket.trim();
|
|
196
|
+
try {
|
|
197
|
+
return iroh.EndpointTicket.fromString(trimmed).endpointAddr();
|
|
198
|
+
} catch {
|
|
199
|
+
return new iroh.EndpointAddr(iroh.EndpointId.fromString(trimmed));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function withTimeout<T>(work: Promise<T>, ms: number, message: string): Promise<T> {
|
|
204
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
205
|
+
const timeout = new Promise<never>((_, reject) => (timer = setTimeout(() => reject(new Error(message)), ms)));
|
|
206
|
+
return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function listenPortPair(): Promise<[net.Server, net.Server]> {
|
|
210
|
+
for (let attempt = 0; attempt < PORT_PAIR_ATTEMPTS; attempt++) {
|
|
211
|
+
const first = net.createServer();
|
|
212
|
+
first.listen(0, '127.0.0.1');
|
|
213
|
+
await once(first, 'listening');
|
|
214
|
+
const port = (first.address() as net.AddressInfo).port;
|
|
215
|
+
const second = net.createServer();
|
|
216
|
+
try {
|
|
217
|
+
second.listen(port + 1, '127.0.0.1');
|
|
218
|
+
await once(second, 'listening');
|
|
219
|
+
return [first, second];
|
|
220
|
+
} catch {
|
|
221
|
+
first.close();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
throw new Error('no adjacent pair of free local ports');
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The phone's side, as the Glassly App's native tunnel does it: two adjacent 127.0.0.1 ports,
|
|
229
|
+
* each TCP connection to port N carried on its own bi-stream to target N with `token`, redialling
|
|
230
|
+
* when the connection drops.
|
|
231
|
+
*/
|
|
232
|
+
export async function dialTunnel(options: {ticket: string; token: string; timeoutMs?: number}): Promise<DialedTunnel> {
|
|
233
|
+
const iroh = await loadIroh();
|
|
234
|
+
if (typeof iroh === 'string') throw new Error(iroh);
|
|
235
|
+
const tokenBytes = Array.from(Buffer.from(options.token));
|
|
236
|
+
if (tokenBytes.length > 255) throw new Error('token longer than 255 bytes');
|
|
237
|
+
const addr = parseAddr(iroh, options.ticket);
|
|
238
|
+
const endpoint = await iroh.Endpoint.bind({});
|
|
239
|
+
const timeoutMs = options.timeoutMs ?? DIAL_TIMEOUT_MS;
|
|
240
|
+
const dial = () => withTimeout(endpoint.connect(addr, ALPN_BYTES), timeoutMs, 'timed out reaching the computer over iroh');
|
|
241
|
+
let conn: Connection;
|
|
242
|
+
try {
|
|
243
|
+
conn = await dial();
|
|
244
|
+
} catch (error) {
|
|
245
|
+
await endpoint.close();
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
const current = async (): Promise<Connection> => {
|
|
249
|
+
if (conn.closeReason() !== null) conn = await dial();
|
|
250
|
+
return conn;
|
|
251
|
+
};
|
|
252
|
+
const sockets = new Set<net.Socket>();
|
|
253
|
+
const forward = async (socket: net.Socket, target: number) => {
|
|
254
|
+
sockets.add(socket);
|
|
255
|
+
socket.once('close', () => sockets.delete(socket));
|
|
256
|
+
try {
|
|
257
|
+
const bi = await (await current()).openBi();
|
|
258
|
+
await bi.send.writeAll([target, tokenBytes.length, ...tokenBytes]);
|
|
259
|
+
await splice(bi, socket);
|
|
260
|
+
} catch {
|
|
261
|
+
socket.destroy();
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
const servers = await listenPortPair();
|
|
265
|
+
servers.forEach((server, target) => server.on('connection', socket => void forward(socket, target)));
|
|
266
|
+
const ports = servers.map(server => (server.address() as net.AddressInfo).port) as [number, number];
|
|
267
|
+
return {
|
|
268
|
+
endpointId: addr.id().toString(),
|
|
269
|
+
ports,
|
|
270
|
+
close: async () => {
|
|
271
|
+
for (const server of servers) server.close();
|
|
272
|
+
for (const socket of sockets) socket.destroy();
|
|
273
|
+
await endpoint.close();
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import {isCancel, password, select} from '@clack/prompts';
|
|
2
|
+
import {loadIroh} from '../iroh-tunnel.js';
|
|
3
|
+
import {printQR, type QRSize} from '../qr.js';
|
|
4
|
+
import {gtermAccepts, gtermAddress, refuseIfRunning, startLinkDaemon} from './daemon.js';
|
|
5
|
+
import {linkHome, loadOrCreateState, loadState, saveState, unpairPhone, type LinkedPhone} from './state.js';
|
|
6
|
+
|
|
7
|
+
export interface LinkOptions {
|
|
8
|
+
pair?: boolean;
|
|
9
|
+
name?: string;
|
|
10
|
+
gterm?: string;
|
|
11
|
+
gtermToken?: string;
|
|
12
|
+
qrSize?: QRSize;
|
|
13
|
+
home?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function describePhones(phones: LinkedPhone[]): string {
|
|
17
|
+
return phones.map(phone => `${phone.name} (${phone.id})`).join(', ');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function link(options: LinkOptions): Promise<void> {
|
|
21
|
+
const iroh = await loadIroh();
|
|
22
|
+
if (typeof iroh === 'string') {
|
|
23
|
+
throw new Error(
|
|
24
|
+
`glassly link runs over iroh, which has no build for this computer (${process.platform}-${process.arch}; Intel Macs have none). Run it on an Apple silicon Mac, Linux or Windows, or reach gterm-server from Terminal by address.`,
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
const dir = linkHome(options.home);
|
|
28
|
+
refuseIfRunning(dir);
|
|
29
|
+
const state = loadOrCreateState(dir, () => iroh.SecretKey.generate().toBytes(), options.name);
|
|
30
|
+
if (options.name) state.name = options.name;
|
|
31
|
+
if (options.gterm) state.gterm.url = options.gterm;
|
|
32
|
+
const gterm = gtermAddress(state.gterm.url);
|
|
33
|
+
const token = options.gtermToken ?? process.env.GTERM_TOKEN ?? state.gterm.token ?? (await askGtermToken());
|
|
34
|
+
state.gterm.token = token;
|
|
35
|
+
saveState(dir, state);
|
|
36
|
+
|
|
37
|
+
if (!(await gtermAccepts(gterm))) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
`gterm-server isn't running at ${state.gterm.url}. Start it with \`gterm-server\`, then run \`glassly link\` again.`,
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const daemon = await startLinkDaemon({dir, iroh, pair: options.pair || state.phones.length === 0, out: line => console.log(line)});
|
|
44
|
+
if (daemon.offerUrl) {
|
|
45
|
+
console.log(`Linking ${daemon.name} to your phone over iroh, peer to peer.`);
|
|
46
|
+
console.log("Scan this with your phone's camera, or in Terminal: Link a computer › Scan code.");
|
|
47
|
+
await printQR(daemon.offerUrl, {size: options.qrSize ?? 'small'});
|
|
48
|
+
console.log(`Or paste this in Terminal: ${daemon.offerUrl}`);
|
|
49
|
+
console.log(`Key ${daemon.fingerprint}. It works once, for 10 minutes. Waiting for your phone…`);
|
|
50
|
+
} else {
|
|
51
|
+
const phones = state.phones;
|
|
52
|
+
console.log(
|
|
53
|
+
`${daemon.name} is linked to ${phones.length} phone${phones.length === 1 ? '' : 's'}: ${describePhones(phones)}. Key ${daemon.fingerprint}. Ready.`,
|
|
54
|
+
);
|
|
55
|
+
console.log('Run `glassly link --pair` to add a phone, `glassly link unpair <name>` to remove one.');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const stopOnSignal = () => void daemon.stop();
|
|
59
|
+
process.once('SIGINT', stopOnSignal);
|
|
60
|
+
process.once('SIGTERM', stopOnSignal);
|
|
61
|
+
await daemon.stopped;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function askGtermToken(): Promise<string> {
|
|
65
|
+
if (!process.stdin.isTTY) {
|
|
66
|
+
throw new Error('No gterm token. Pass --gterm-token, or set GTERM_TOKEN, then run `glassly link` again.');
|
|
67
|
+
}
|
|
68
|
+
const answer = await password({message: "gterm-server's token (kept in ~/.glassly/link, only sent to your phone)"});
|
|
69
|
+
if (isCancel(answer)) throw new Error('Cancelled.');
|
|
70
|
+
return answer;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function linkUnpair(nameOrId: string, options: {home?: string} = {}): Promise<void> {
|
|
74
|
+
const dir = linkHome(options.home);
|
|
75
|
+
let result = unpairPhone(dir, nameOrId);
|
|
76
|
+
if (result.status === 'ambiguous') {
|
|
77
|
+
const matches = result.matches;
|
|
78
|
+
if (!process.stdin.isTTY) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
`${matches.length} phones are named ${nameOrId}: ${describePhones(matches)}. Run \`glassly link unpair <id>\` with one of these ids.`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
const choice = await select({
|
|
84
|
+
message: `${matches.length} phones are named ${nameOrId}. Which one?`,
|
|
85
|
+
options: matches.map(phone => ({value: phone.id, label: `${phone.name} (${phone.id})`, hint: `linked ${phone.linkedAt.slice(0, 10)}`})),
|
|
86
|
+
});
|
|
87
|
+
if (isCancel(choice)) throw new Error('Cancelled.');
|
|
88
|
+
result = unpairPhone(dir, choice);
|
|
89
|
+
}
|
|
90
|
+
if (result.status !== 'removed') {
|
|
91
|
+
const phones = loadState(dir)?.phones ?? [];
|
|
92
|
+
throw new Error(
|
|
93
|
+
phones.length
|
|
94
|
+
? `No linked phone is called ${nameOrId}. Linked: ${describePhones(phones)}.`
|
|
95
|
+
: 'No phones are linked to this computer.',
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
console.log(`Removed ${result.phone.name} (${result.phone.id}). It can't connect to this computer anymore.`);
|
|
99
|
+
console.log(
|
|
100
|
+
'If gterm-server also listens beyond this computer, change its token too; linked phones get the new one when they next connect.',
|
|
101
|
+
);
|
|
102
|
+
}
|