@glassly/miniapp-cli 0.1.17 → 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.
@@ -0,0 +1,338 @@
1
+ /**
2
+ * The `glassly link` daemon: one iroh endpoint, keyed by the state file so its id survives
3
+ * restarts. The control target is an HTTP API served in this process, the service target a raw TCP
4
+ * pipe to gterm-server. Any app on the phone can open streams on a phone's route, so their header
5
+ * token means nothing here: each control request carries `Authorization: Bearer <token>` and each
6
+ * service upgrade `?link=<token>` (`@glassly/miniapp/link`), and `callerOf` checks both. It opens
7
+ * no listening port and reaches no address other than gterm-server.
8
+ */
9
+ import {timingSafeEqual} from 'crypto';
10
+ import {existsSync, readFileSync, rmSync, watch, writeFileSync} from 'fs';
11
+ import http from 'http';
12
+ import type net from 'net';
13
+ import {join} from 'path';
14
+ import type {BiStream, Connection, Endpoint} from '@number0/iroh';
15
+ import {
16
+ createOffer,
17
+ keyFingerprint,
18
+ LINK_PATHS,
19
+ LINK_REFUSAL_STATUS,
20
+ LINK_TARGET,
21
+ offerToUrl,
22
+ parseLinkToken,
23
+ randomSecret,
24
+ type LinkRefusal,
25
+ type PairReply,
26
+ type WelcomeReply,
27
+ } from '@glassly/miniapp/link';
28
+ import {
29
+ acceptConnections,
30
+ acceptStreams,
31
+ bindEndpoint,
32
+ connectTcp,
33
+ describePath,
34
+ readHeader,
35
+ refuse,
36
+ splice,
37
+ streamSocket,
38
+ type Iroh,
39
+ } from '../iroh-tunnel.js';
40
+ import {loadOrCreateState, loadState, updateState, type LinkedPhone} from './state.js';
41
+ import {readUpgrade, refuseUpgrade} from './upgrade.js';
42
+
43
+ const OFFER_LIFETIME_MS = 10 * 60_000;
44
+ const GTERM_PROBE_TIMEOUT_MS = 2_000;
45
+ const MAX_BODY_BYTES = 4096;
46
+ const MAX_PHONE_NAME = 64;
47
+
48
+ export interface LinkDaemonOptions {
49
+ dir: string;
50
+ iroh: Iroh;
51
+ pair: boolean;
52
+ out: (line: string) => void;
53
+ offerLifetimeMs?: number;
54
+ }
55
+
56
+ export interface LinkDaemon {
57
+ name: string;
58
+ endpointId: string;
59
+ fingerprint: string;
60
+ offerUrl: string | null;
61
+ stopped: Promise<void>;
62
+ stop(): Promise<void>;
63
+ }
64
+
65
+ export interface GtermAddress {
66
+ host: string;
67
+ port: number;
68
+ }
69
+
70
+ type ControlReply = {status: 200; body: PairReply | WelcomeReply} | {status: number; body: {error: LinkRefusal | 'not_found'}};
71
+ type Caller = {kind: 'pair'; secret: string} | {kind: 'phone'; phone: LinkedPhone} | null;
72
+ type ControlRoute = (caller: Caller, body: string, conn: Connection) => Promise<ControlReply>;
73
+ type ServiceStream = {bi: BiStream; socket: net.Socket};
74
+
75
+ const refusal = (error: LinkRefusal): ControlReply => ({status: LINK_REFUSAL_STATUS[error], body: {error}});
76
+
77
+ export function gtermAddress(url: string): GtermAddress {
78
+ const parsed = new URL(url);
79
+ if (parsed.protocol !== 'ws:') {
80
+ throw new Error(`glassly link forwards raw TCP, so --gterm must be a ws:// address, like ws://127.0.0.1:8737, not ${url}.`);
81
+ }
82
+ return {host: parsed.hostname.replace(/^\[|\]$/g, ''), port: Number(parsed.port) || 80};
83
+ }
84
+
85
+ export async function gtermAccepts(address: GtermAddress, timeoutMs = GTERM_PROBE_TIMEOUT_MS): Promise<boolean> {
86
+ let timer: ReturnType<typeof setTimeout> | undefined;
87
+ const timeout = new Promise<null>(resolve => (timer = setTimeout(() => resolve(null), timeoutMs)));
88
+ const socket = await Promise.race([connectTcp(address.host, address.port).catch(() => null), timeout]);
89
+ clearTimeout(timer);
90
+ socket?.destroy();
91
+ return socket !== null;
92
+ }
93
+
94
+ function secretMatches(presented: string, expected: string): boolean {
95
+ const got = Buffer.from(presented);
96
+ const want = Buffer.from(expected);
97
+ return got.length === want.length && timingSafeEqual(got, want);
98
+ }
99
+
100
+ function bearerOf(header: string | undefined): string | null {
101
+ return /^Bearer (\S+)$/i.exec(header ?? '')?.[1] ?? null;
102
+ }
103
+
104
+ function readBody(request: http.IncomingMessage): Promise<string> {
105
+ return new Promise((resolve, reject) => {
106
+ let body = '';
107
+ request.setEncoding('utf8');
108
+ request.on('data', (chunk: string) => {
109
+ body += chunk;
110
+ if (body.length > MAX_BODY_BYTES) request.destroy(new Error('body too large'));
111
+ });
112
+ request.on('end', () => resolve(body));
113
+ request.on('error', reject);
114
+ });
115
+ }
116
+
117
+ // The name is printed to this computer's terminal, so control characters (ANSI escapes among them)
118
+ // never get through.
119
+ function phoneNameFrom(body: string): string {
120
+ try {
121
+ const name = (JSON.parse(body) as {phoneName?: unknown}).phoneName;
122
+ const printable = typeof name === 'string' ? name.replace(/\p{Cc}/gu, '').trim() : '';
123
+ if (printable) return printable.slice(0, MAX_PHONE_NAME);
124
+ } catch {
125
+ return 'Phone';
126
+ }
127
+ return 'Phone';
128
+ }
129
+
130
+ const lockPath = (dir: string) => join(dir, 'daemon.pid');
131
+
132
+ export function refuseIfRunning(dir: string): void {
133
+ const holder = existsSync(lockPath(dir)) ? Number(readFileSync(lockPath(dir), 'utf8')) : 0;
134
+ if (holder && holder !== process.pid && isRunning(holder)) {
135
+ throw new Error(`glassly link is already running on this computer (pid ${holder}). Stop it first, then run this again.`);
136
+ }
137
+ }
138
+
139
+ function holdLock(dir: string): () => void {
140
+ refuseIfRunning(dir);
141
+ writeFileSync(lockPath(dir), String(process.pid), {mode: 0o600});
142
+ return () => rmSync(lockPath(dir), {force: true});
143
+ }
144
+
145
+ function isRunning(pid: number): boolean {
146
+ try {
147
+ process.kill(pid, 0);
148
+ return true;
149
+ } catch (error) {
150
+ return (error as NodeJS.ErrnoException).code === 'EPERM';
151
+ }
152
+ }
153
+
154
+ export async function startLinkDaemon(options: LinkDaemonOptions): Promise<LinkDaemon> {
155
+ const {dir, iroh, out} = options;
156
+ const state = loadOrCreateState(dir, () => iroh.SecretKey.generate().toBytes());
157
+ const gterm = gtermAddress(state.gterm.url);
158
+ const releaseLock = holdLock(dir);
159
+ let endpoint: Endpoint;
160
+ try {
161
+ endpoint = await bindEndpoint(iroh, Array.from(Buffer.from(state.secretKey, 'hex')));
162
+ } catch (error) {
163
+ releaseLock();
164
+ throw error;
165
+ }
166
+ const endpointId = endpoint.id().toString();
167
+ const offer = options.pair
168
+ ? createOffer({ticket: iroh.EndpointTicket.fromAddr(endpoint.addr()).toString(), id: endpointId, name: state.name})
169
+ : null;
170
+ let offerOpen = offer !== null;
171
+ const offerLifetimeMs = options.offerLifetimeMs ?? OFFER_LIFETIME_MS;
172
+ const offerExpiresAt = Date.now() + offerLifetimeMs;
173
+ const offerExpiry = offer
174
+ ? setTimeout(() => {
175
+ if (!offerOpen) return;
176
+ offerOpen = false;
177
+ out('The pairing code expired with no phone linked. For a new one, press Ctrl+C and run `glassly link --pair`.');
178
+ }, offerLifetimeMs)
179
+ : undefined;
180
+ const services = new Map<string, Set<ServiceStream>>();
181
+ const controlConnections = new WeakMap<object, Connection>();
182
+ const announced = new WeakSet<Connection>();
183
+ const liveByRemote = new Map<string, number>();
184
+
185
+ const takeOffer = (secret: string): boolean => {
186
+ if (!offer || !offerOpen || !secretMatches(secret, offer.secret)) return false;
187
+ offerOpen = false;
188
+ return Date.now() < offerExpiresAt;
189
+ };
190
+
191
+ const callerOf = (credential: string | null): Caller => {
192
+ const token = credential ? parseLinkToken(credential) : null;
193
+ if (token?.kind !== 'phone') return token;
194
+ const phone = loadState(dir)?.phones.find(entry => entry.id === token.phoneId);
195
+ return phone && secretMatches(token.secret, phone.secret) ? {kind: 'phone', phone} : null;
196
+ };
197
+
198
+ const announce = (conn: Connection, phoneName: string) => {
199
+ if (announced.has(conn)) return;
200
+ announced.add(conn);
201
+ const remote = conn.remoteId().toString();
202
+ const live = liveByRemote.get(remote) ?? 0;
203
+ liveByRemote.set(remote, live + 1);
204
+ if (live === 0) out(`${phoneName} connected over iroh (${describePath(conn)}).`);
205
+ void conn.closed().catch(() => {}).finally(() => {
206
+ const left = (liveByRemote.get(remote) ?? 1) - 1;
207
+ if (left > 0) liveByRemote.set(remote, left);
208
+ else liveByRemote.delete(remote);
209
+ });
210
+ };
211
+
212
+ const routes: Record<string, ControlRoute> = {
213
+ [`POST ${LINK_PATHS.pair}`]: async (caller, body, conn) => {
214
+ if (caller?.kind !== 'pair' || !takeOffer(caller.secret)) return refusal('code_used');
215
+ const phone: LinkedPhone = {
216
+ id: randomSecret(6),
217
+ name: phoneNameFrom(body),
218
+ secret: randomSecret(32),
219
+ linkedAt: new Date().toISOString(),
220
+ };
221
+ const current = updateState(dir, next => next.phones.push(phone));
222
+ announced.add(conn);
223
+ out(`Linked ${phone.name} (${describePath(conn)}). Keep this running to use Terminal from your phone. Ctrl+C stops it.`);
224
+ return {
225
+ status: 200,
226
+ body: {phoneId: phone.id, phoneSecret: phone.secret, name: current.name, gtermToken: current.gterm.token ?? ''},
227
+ };
228
+ },
229
+ [`GET ${LINK_PATHS.welcome}`]: async (caller, _body, conn) => {
230
+ if (caller?.kind !== 'phone') return refusal('not_linked');
231
+ announce(conn, caller.phone.name);
232
+ if (!(await gtermAccepts(gterm))) return refusal('gterm_down');
233
+ const current = loadState(dir) ?? state;
234
+ return {status: 200, body: {name: current.name, gtermToken: current.gterm.token ?? ''}};
235
+ },
236
+ };
237
+
238
+ const server = http.createServer(async (request, response) => {
239
+ const conn = controlConnections.get(request.socket);
240
+ const route = routes[`${request.method} ${request.url}`];
241
+ if (!conn) return void response.destroy();
242
+ try {
243
+ const body = await readBody(request);
244
+ const reply: ControlReply = route
245
+ ? await route(callerOf(bearerOf(request.headers.authorization)), body, conn)
246
+ : {status: 404, body: {error: 'not_found'}};
247
+ response.writeHead(reply.status, {'content-type': 'application/json'}).end(JSON.stringify(reply.body));
248
+ } catch {
249
+ response.destroy();
250
+ }
251
+ });
252
+
253
+ const serveService = async (bi: BiStream, conn: Connection) => {
254
+ const upgrade = await readUpgrade(bi.recv);
255
+ const caller = callerOf(upgrade?.credential ?? null);
256
+ if (!upgrade || caller?.kind !== 'phone') return refuseUpgrade(bi, 'not_linked');
257
+ const {phone} = caller;
258
+ const socket = await connectTcp(gterm.host, gterm.port).catch(() => null);
259
+ if (!socket) return refuseUpgrade(bi, 'gterm_down');
260
+ if (callerOf(upgrade.credential)?.kind !== 'phone') {
261
+ socket.destroy();
262
+ return refuseUpgrade(bi, 'not_linked');
263
+ }
264
+ announce(conn, phone.name);
265
+ socket.write(upgrade.forwarded);
266
+ const stream = {bi, socket};
267
+ const open = services.get(phone.id) ?? new Set<ServiceStream>();
268
+ services.set(phone.id, open.add(stream));
269
+ try {
270
+ await splice(bi, socket);
271
+ } finally {
272
+ open.delete(stream);
273
+ }
274
+ };
275
+
276
+ const targets: Record<number, (bi: BiStream, conn: Connection) => Promise<void>> = {
277
+ [LINK_TARGET.control]: async (bi, conn) => {
278
+ const socket = streamSocket(bi);
279
+ controlConnections.set(socket, conn);
280
+ server.emit('connection', socket);
281
+ },
282
+ [LINK_TARGET.service]: serveService,
283
+ };
284
+
285
+ const onStream = async (bi: BiStream, conn: Connection) => {
286
+ const header = await readHeader(bi.recv);
287
+ const serve = header && targets[header.target];
288
+ if (!serve) return refuse(bi);
289
+ await serve(bi, conn);
290
+ };
291
+
292
+ const closeService = ({bi, socket}: ServiceStream) => {
293
+ socket.destroy();
294
+ void refuse(bi);
295
+ };
296
+
297
+ const dropUnpairedPhones = () => {
298
+ const linked = new Set(loadState(dir)?.phones.map(phone => phone.id) ?? []);
299
+ for (const [phoneId, open] of services) {
300
+ if (linked.has(phoneId)) continue;
301
+ open.forEach(closeService);
302
+ services.delete(phoneId);
303
+ }
304
+ };
305
+ const watcher = watch(dir, () => {
306
+ try {
307
+ dropUnpairedPhones();
308
+ } catch {
309
+ return;
310
+ }
311
+ });
312
+
313
+ void acceptConnections(endpoint, conn => acceptStreams(conn, bi => onStream(bi, conn)));
314
+
315
+ let markStopped: () => void = () => {};
316
+ const stopped = new Promise<void>(resolve => (markStopped = resolve));
317
+ let stopping: Promise<void> | null = null;
318
+ const stop = () =>
319
+ (stopping ??= (async () => {
320
+ watcher.close();
321
+ clearTimeout(offerExpiry);
322
+ for (const open of services.values()) open.forEach(closeService);
323
+ services.clear();
324
+ server.close();
325
+ await endpoint.close().catch(() => {});
326
+ releaseLock();
327
+ markStopped();
328
+ })());
329
+
330
+ return {
331
+ name: state.name,
332
+ endpointId,
333
+ fingerprint: keyFingerprint(endpointId),
334
+ offerUrl: offer ? offerToUrl(offer) : null,
335
+ stopped,
336
+ stop,
337
+ };
338
+ }
@@ -0,0 +1,357 @@
1
+ import {afterEach, beforeAll, describe, expect, test} from 'bun:test';
2
+ import {once} from 'events';
3
+ import {mkdtempSync, rmSync, statSync, writeFileSync} from 'fs';
4
+ import net from 'net';
5
+ import os from 'os';
6
+ import {join} from 'path';
7
+ import {MiniappSession, type Transport} from '@glassly/miniapp';
8
+ import {pairingToken, parseOffer, phoneToken, type LinkOffer} from '@glassly/miniapp/link';
9
+ import {simDevice} from '../sim/device.js';
10
+ import {SimHost} from '../sim/host.js';
11
+ import {createSimStorage} from '../sim/storage.js';
12
+ import {dialTunnel, loadIroh, type DialedTunnel, type Iroh} from '../iroh-tunnel.js';
13
+ import {startLinkDaemon, type LinkDaemon} from './daemon.js';
14
+ import {saveState, statePath, unpairPhone} from './state.js';
15
+
16
+ const GTERM_TOKEN = 'gterm-secret-token';
17
+ const tunnels: DialedTunnel[] = [];
18
+
19
+ interface Route {
20
+ control: string;
21
+ service: string;
22
+ servicePort: number;
23
+ endpointId: string;
24
+ }
25
+
26
+ async function phone(ticket: string, headerToken = ''): Promise<Route> {
27
+ const tunnel = await dialTunnel({ticket, token: headerToken});
28
+ tunnels.push(tunnel);
29
+ return {
30
+ control: `http://127.0.0.1:${tunnel.ports[0]}`,
31
+ service: `ws://127.0.0.1:${tunnel.ports[1]}`,
32
+ servicePort: tunnel.ports[1],
33
+ endpointId: tunnel.endpointId,
34
+ };
35
+ }
36
+
37
+ const bearer = (credential: string) => ({headers: {authorization: `Bearer ${credential}`}});
38
+ const serviceUrl = (route: Route, credential: string) => `${route.service}/?link=${encodeURIComponent(credential)}`;
39
+
40
+ async function call(url: string, init?: RequestInit): Promise<{status: number; body: Record<string, string>}> {
41
+ const response = await fetch(url, init);
42
+ return {status: response.status, body: (await response.json()) as Record<string, string>};
43
+ }
44
+
45
+ function openSocket(url: string): Promise<WebSocket> {
46
+ return new Promise((resolve, reject) => {
47
+ const socket = new WebSocket(url);
48
+ socket.onopen = () => resolve(socket);
49
+ socket.onerror = () => reject(new Error(`no WebSocket at ${url}`));
50
+ });
51
+ }
52
+
53
+ function nextMessage(socket: WebSocket): Promise<string> {
54
+ return new Promise(resolve => (socket.onmessage = event => resolve(String(event.data))));
55
+ }
56
+
57
+ function closed(socket: WebSocket): Promise<void> {
58
+ return new Promise(resolve => {
59
+ if (socket.readyState === WebSocket.CLOSED) resolve();
60
+ socket.addEventListener('close', () => resolve());
61
+ });
62
+ }
63
+
64
+ async function upgradeStatus(port: number, target: string): Promise<number> {
65
+ const socket = net.connect(port, '127.0.0.1');
66
+ await once(socket, 'connect');
67
+ socket.write(
68
+ `GET ${target} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
69
+ 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n',
70
+ );
71
+ let reply = '';
72
+ socket.on('data', chunk => (reply += chunk.toString('latin1')));
73
+ await Promise.race([once(socket, 'close'), new Promise(resolve => setTimeout(resolve, 5_000))]);
74
+ socket.destroy();
75
+ return Number(/^HTTP\/1\.1 (\d{3})/.exec(reply)?.[1] ?? 0);
76
+ }
77
+
78
+ interface Gterm {
79
+ port: number;
80
+ received: string[];
81
+ stop(): void;
82
+ }
83
+
84
+ interface Computer {
85
+ dir: string;
86
+ daemon: LinkDaemon;
87
+ offer: LinkOffer;
88
+ gterm: Gterm;
89
+ lines: string[];
90
+ }
91
+
92
+ const computers: Computer[] = [];
93
+ let iroh: Iroh;
94
+
95
+ async function startGterm(port = 0): Promise<Gterm> {
96
+ const echo = Bun.serve({
97
+ port: 0,
98
+ hostname: '127.0.0.1',
99
+ fetch: (request, server) => (server.upgrade(request) ? undefined : new Response('gterm', {status: 426})),
100
+ websocket: {
101
+ message: (socket, message) => {
102
+ socket.send(`echo:${message}`);
103
+ },
104
+ },
105
+ });
106
+ const received: string[] = [];
107
+ const sockets = new Set<net.Socket>();
108
+ const front = net.createServer(socket => {
109
+ sockets.add(socket);
110
+ const upstream = net.connect(echo.port!, '127.0.0.1');
111
+ let index = -1;
112
+ socket.on('data', chunk => {
113
+ if (index < 0) index = received.push('') - 1;
114
+ received[index] += chunk.toString('latin1');
115
+ });
116
+ socket.pipe(upstream).pipe(socket);
117
+ socket.on('close', () => upstream.destroy());
118
+ upstream.on('close', () => socket.destroy());
119
+ socket.on('error', () => {});
120
+ upstream.on('error', () => {});
121
+ });
122
+ front.listen(port, '127.0.0.1');
123
+ await once(front, 'listening');
124
+ return {
125
+ port: (front.address() as net.AddressInfo).port,
126
+ received,
127
+ stop: () => {
128
+ front.close();
129
+ sockets.forEach(socket => socket.destroy());
130
+ echo.stop(true);
131
+ },
132
+ };
133
+ }
134
+
135
+ async function computer(options: {offerLifetimeMs?: number} = {}): Promise<Computer> {
136
+ const dir = mkdtempSync(join(os.tmpdir(), 'glassly-link-'));
137
+ const gterm = await startGterm();
138
+ saveState(dir, {
139
+ version: 2,
140
+ name: 'test-mac',
141
+ secretKey: Buffer.from(iroh.SecretKey.generate().toBytes()).toString('hex'),
142
+ phones: [],
143
+ gterm: {url: `ws://127.0.0.1:${gterm.port}`, token: GTERM_TOKEN},
144
+ });
145
+ const lines: string[] = [];
146
+ const daemon = await startLinkDaemon({dir, iroh, pair: true, out: line => lines.push(line), ...options});
147
+ const started = {dir, daemon, offer: parseOffer(daemon.offerUrl!), gterm, lines};
148
+ computers.push(started);
149
+ return started;
150
+ }
151
+
152
+ async function pair(at: Computer, phoneName: string): Promise<{credential: string; phoneSecret: string}> {
153
+ const route = await phone(at.offer.ticket);
154
+ const pairing = {method: 'POST', body: JSON.stringify({phoneName}), ...bearer(pairingToken(at.offer.secret))};
155
+ const reply = await call(`${route.control}/pair`, pairing);
156
+ expect(reply.status).toBe(200);
157
+ return {credential: phoneToken(reply.body.phoneId, reply.body.phoneSecret), phoneSecret: reply.body.phoneSecret};
158
+ }
159
+
160
+ beforeAll(async () => {
161
+ const loaded = await loadIroh();
162
+ if (typeof loaded === 'string') throw new Error(loaded);
163
+ iroh = loaded;
164
+ });
165
+
166
+ afterEach(async () => {
167
+ await Promise.all(tunnels.splice(0).map(tunnel => tunnel.close()));
168
+ for (const {daemon, gterm, dir} of computers.splice(0)) {
169
+ await daemon.stop();
170
+ gterm.stop();
171
+ rmSync(dir, {recursive: true, force: true});
172
+ }
173
+ });
174
+
175
+ describe('glassly link over iroh', () => {
176
+ test('a phone pairs once with the code, reaches gterm-server, and loses both when unpaired', async () => {
177
+ const mac = await computer();
178
+ expect(mac.offer).toMatchObject({v: 2, id: mac.daemon.endpointId, name: 'test-mac'});
179
+ expect(statSync(statePath(mac.dir)).mode & 0o777).toBe(0o600);
180
+ expect(statSync(mac.dir).mode & 0o777).toBe(0o700);
181
+
182
+ const route = await phone(mac.offer.ticket);
183
+ expect(route.endpointId).toBe(mac.offer.id);
184
+ const pairing = {method: 'POST', ...bearer(pairingToken(mac.offer.secret))};
185
+ const first = await call(`${route.control}/pair`, {...pairing, body: JSON.stringify({phoneName: 'Test phone'})});
186
+ expect(first.status).toBe(200);
187
+ expect(first.body).toMatchObject({name: 'test-mac', gtermToken: GTERM_TOKEN});
188
+ expect(first.body.phoneId).toMatch(/^[A-Za-z0-9_-]{8}$/);
189
+ expect(first.body.phoneSecret).toMatch(/^[A-Za-z0-9_-]{43}$/);
190
+ expect(mac.lines.find(line => line.startsWith('Linked Test phone'))).toMatch(/^Linked Test phone \((direct|relay)/);
191
+ expect(await call(`${route.control}/pair`, {...pairing, body: '{}'})).toEqual({status: 410, body: {error: 'code_used'}});
192
+
193
+ const credential = phoneToken(first.body.phoneId, first.body.phoneSecret);
194
+ expect(await call(`${route.control}/welcome`, bearer(credential))).toEqual({
195
+ status: 200,
196
+ body: {name: 'test-mac', gtermToken: GTERM_TOKEN},
197
+ });
198
+ const socket = await openSocket(serviceUrl(route, credential));
199
+ const reply = nextMessage(socket);
200
+ socket.send('ls -la\r');
201
+ expect(await reply).toBe('echo:ls -la\r');
202
+
203
+ const gone = closed(socket);
204
+ expect(unpairPhone(mac.dir, 'Test phone')).toMatchObject({status: 'removed'});
205
+ await gone;
206
+ expect(await call(`${route.control}/welcome`, bearer(credential))).toEqual({status: 401, body: {error: 'not_linked'}});
207
+ await expect(openSocket(serviceUrl(route, credential))).rejects.toThrow();
208
+ }, 30_000);
209
+
210
+ test("codes, tokens and secrets that are not this phone's open nothing", async () => {
211
+ const mac = await computer();
212
+ const route = await phone(mac.offer.ticket);
213
+ const stranger = pairingToken('AAAAAAAAAAAAAAAAAAAAAA');
214
+ expect(await call(`${route.control}/pair`, {method: 'POST', body: '{}', ...bearer(stranger)})).toEqual({
215
+ status: 410,
216
+ body: {error: 'code_used'},
217
+ });
218
+ expect(await call(`${route.control}/pair`, {method: 'POST', body: '{}'})).toEqual({status: 410, body: {error: 'code_used'}});
219
+ expect(await upgradeStatus(route.servicePort, `/?link=${pairingToken(mac.offer.secret)}`)).toBe(401);
220
+ expect(await call(`${route.control}/welcome`, bearer('not-a-link-token'))).toEqual({
221
+ status: 401,
222
+ body: {error: 'not_linked'},
223
+ });
224
+
225
+ const linked = await pair(mac, 'Phone A');
226
+ const wrongSecret = linked.credential.replace(linked.phoneSecret, 'x'.repeat(43));
227
+ expect(await call(`${route.control}/welcome`, bearer(wrongSecret))).toEqual({status: 401, body: {error: 'not_linked'}});
228
+ expect(await upgradeStatus(route.servicePort, `/?link=${encodeURIComponent(wrongSecret)}`)).toBe(401);
229
+ expect(mac.gterm.received).toEqual([]);
230
+ }, 30_000);
231
+
232
+ test('another app on the phone, with no credential of its own, gets 401 and gterm-server hears nothing', async () => {
233
+ const mac = await computer();
234
+ const linked = await pair(mac, 'Phone A');
235
+ for (const headerToken of [linked.credential, '']) {
236
+ const route = await phone(mac.offer.ticket, headerToken);
237
+ expect(await call(`${route.control}/welcome`)).toEqual({status: 401, body: {error: 'not_linked'}});
238
+ expect(await upgradeStatus(route.servicePort, '/')).toBe(401);
239
+ }
240
+ expect(mac.gterm.received).toEqual([]);
241
+ }, 30_000);
242
+
243
+ test("a linked phone's credential opens the welcome and the service, and gterm-server never sees it", async () => {
244
+ const mac = await computer();
245
+ const linked = await pair(mac, 'Phone A');
246
+ const route = await phone(mac.offer.ticket);
247
+ expect(await call(`${route.control}/welcome`, bearer(linked.credential))).toEqual({
248
+ status: 200,
249
+ body: {name: 'test-mac', gtermToken: GTERM_TOKEN},
250
+ });
251
+
252
+ const socket = await openSocket(serviceUrl(route, linked.credential));
253
+ const reply = nextMessage(socket);
254
+ socket.send('pwd\r');
255
+ expect(await reply).toBe('echo:pwd\r');
256
+ expect(mac.gterm.received).toHaveLength(1);
257
+ const [forwarded] = mac.gterm.received;
258
+ expect(forwarded.split('\r\n')[0]).toBe('GET / HTTP/1.1');
259
+ expect(forwarded).not.toContain('link=');
260
+ expect(forwarded).not.toContain(linked.phoneSecret);
261
+ socket.close();
262
+ }, 30_000);
263
+
264
+ test('a restart keeps the endpoint id, and a stopped gterm-server answers 503', async () => {
265
+ const mac = await computer();
266
+ const linked = await pair(mac, 'Phone B');
267
+ const firstId = mac.daemon.endpointId;
268
+ await mac.daemon.stop();
269
+ mac.daemon = await startLinkDaemon({dir: mac.dir, iroh, pair: false, out: () => {}});
270
+ expect(mac.daemon.endpointId).toBe(firstId);
271
+
272
+ const route = await phone(mac.offer.ticket);
273
+ const welcome = () => call(`${route.control}/welcome`, bearer(linked.credential));
274
+ expect((await welcome()).status).toBe(200);
275
+ const port = mac.gterm.port;
276
+ mac.gterm.stop();
277
+ expect(await welcome()).toEqual({status: 503, body: {error: 'gterm_down'}});
278
+ expect(await upgradeStatus(route.servicePort, `/?link=${encodeURIComponent(linked.credential)}`)).toBe(503);
279
+ mac.gterm = await startGterm(port);
280
+ expect((await welcome()).status).toBe(200);
281
+ }, 30_000);
282
+
283
+ test('glassly sim answers session.link.open with a route that pairs', async () => {
284
+ const mac = await computer();
285
+ let deliver: (raw: string) => void = () => {};
286
+ const host = new SimHost({
287
+ manifest: {packageName: 'com.glassly.terminal', name: 'Terminal'},
288
+ device: simDevice('simulated'),
289
+ storage: createSimStorage(),
290
+ toBackground: raw => queueMicrotask(() => deliver(raw)),
291
+ emit: () => {},
292
+ frameLatencyMs: 0,
293
+ speechMsPerChar: 0,
294
+ });
295
+ const transport: Transport = {
296
+ open: async () => {},
297
+ send: raw => queueMicrotask(() => host.fromBackground(raw)),
298
+ onMessage: handler => {
299
+ deliver = handler;
300
+ },
301
+ onDisconnect: () => {},
302
+ close: () => {},
303
+ isOpen: () => true,
304
+ };
305
+ host.backgroundStarted();
306
+ const session = new MiniappSession({transport, packageName: 'com.glassly.terminal'});
307
+ await session.connect();
308
+ try {
309
+ const route = await session.link.open({ticket: mac.offer.ticket});
310
+ expect(route).toMatchObject({endpointId: mac.offer.id, host: '127.0.0.1'});
311
+ expect(route.servicePort).toBe(route.controlPort + 1);
312
+ const paired = await call(`http://127.0.0.1:${route.controlPort}/pair`, {
313
+ method: 'POST',
314
+ body: '{"phoneName":"Sim"}',
315
+ ...bearer(pairingToken(mac.offer.secret)),
316
+ });
317
+ expect(paired).toMatchObject({status: 200, body: {name: 'test-mac', gtermToken: GTERM_TOKEN}});
318
+ expect(await session.link.open({ticket: mac.offer.ticket})).toEqual(route);
319
+ await expect(session.link.open({ticket: 'not a ticket'})).rejects.toMatchObject({code: 'LINK_UNREACHABLE'});
320
+ } finally {
321
+ host.backgroundStopped(false);
322
+ }
323
+ }, 30_000);
324
+
325
+ test('a phone name loses its control characters before the computer stores or prints it', async () => {
326
+ const mac = await computer();
327
+ await pair(mac, '\u001b[2J\u001b]0;pwned\u0007Test\u009b31m phone\u007f');
328
+ const printed = mac.lines.find(line => line.startsWith('Linked '));
329
+ expect(printed).toMatch(/^Linked \[2J\]0;pwnedTest31m phone \((direct|relay)/);
330
+ expect(unpairPhone(mac.dir, '[2J]0;pwnedTest31m phone')).toMatchObject({status: 'removed'});
331
+ }, 30_000);
332
+
333
+ test('an unused code expires with a line that says how to get a new one', async () => {
334
+ const mac = await computer({offerLifetimeMs: 1_000});
335
+ const expired = 'The pairing code expired with no phone linked. For a new one, press Ctrl+C and run `glassly link --pair`.';
336
+ while (!mac.lines.includes(expired)) await Bun.sleep(50);
337
+ const route = await phone(mac.offer.ticket);
338
+ const pairing = {method: 'POST', body: '{"phoneName":"Late phone"}', ...bearer(pairingToken(mac.offer.secret))};
339
+ expect(await call(`${route.control}/pair`, pairing)).toEqual({status: 410, body: {error: 'code_used'}});
340
+ expect(mac.lines).toEqual([expired]);
341
+ }, 30_000);
342
+
343
+ test('a code a phone used never reports expiring', async () => {
344
+ const mac = await computer({offerLifetimeMs: 3_000});
345
+ await pair(mac, 'Phone A');
346
+ await Bun.sleep(3_500);
347
+ expect(mac.lines.filter(line => line.includes('expired'))).toEqual([]);
348
+ }, 30_000);
349
+
350
+ test('a second glassly link on the same state refuses to start', async () => {
351
+ const mac = await computer();
352
+ writeFileSync(join(mac.dir, 'daemon.pid'), String(process.ppid));
353
+ await expect(startLinkDaemon({dir: mac.dir, iroh, pair: false, out: () => {}})).rejects.toThrow(
354
+ `glassly link is already running on this computer (pid ${process.ppid}). Stop it first, then run this again.`,
355
+ );
356
+ }, 30_000);
357
+ });