@glassly/miniapp-cli 0.1.9 → 0.1.10-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/README.md CHANGED
@@ -37,6 +37,7 @@ Run `glassly --help` to print the same list.
37
37
  glassly dev
38
38
  glassly dev --qr lg # QR size: sm | md | lg (default md); -q also works
39
39
  glassly dev --qr-output ./qr.png # also write the QR as a PNG, kept after exit
40
+ glassly dev --no-iroh # LAN-only QR
40
41
  ```
41
42
 
42
43
  What it does:
@@ -46,12 +47,13 @@ What it does:
46
47
  3. Picks the first free adjacent port pair starting at `port`: one for static files and the next for the dev sidecar.
47
48
  4. Starts a static server that serves `miniapp.json`, `icon.png`, and project files.
48
49
  5. Starts a **dev sidecar** on `port + 1`, a WebSocket the phone connects to for live reload + console-log forwarding back to your terminal. Failure here is non-fatal; the miniapp still runs without live reload.
49
- 6. Detects the LAN IP, builds a `miniapp://dev?url=…&name=…&package=…&dev=<sidecarPort>` URL, and prints a terminal QR + the raw URL.
50
- 7. Watches for LAN-IP changes (Wi-Fi switch) every 2s and reprints the QR.
50
+ 6. Binds an [iroh](https://www.iroh.computer) endpoint (key kept per package in `~/.glassly/dev-tunnel/`) that forwards authenticated phone streams to both servers. Skipped with `--no-iroh` or where `@number0/iroh` has no binding (Intel Macs).
51
+ 7. Detects the LAN IP, builds a `miniapp://dev?url=…&name=…&package=…&dev=<sidecarPort>&iroh=<ticket>&token=…` URL, and prints a terminal QR + the raw URL. Older Glassly App builds ignore `iroh`/`token` and use `url`.
52
+ 8. Watches for LAN-IP changes (Wi-Fi switch) every 2s and reprints the QR.
51
53
 
52
54
  Default `port` is `3000`; override the starting point with a `"port": <n>` field in `miniapp.json`. If that port or its sidecar neighbor is busy, `dev` scans upward until it finds a free adjacent pair.
53
55
 
54
- On the phone, open the Glassly App → **Settings → Miniapp Developer Settings → Scan Miniapp QR Code**. That settings row only appears with debug mode on. Phone and laptop must be on the same Wi-Fi.
56
+ On the phone, open the Glassly App → **Settings → Miniapp Developer Settings → Scan Miniapp QR Code**. That settings row only appears with debug mode on. With the iroh ticket the phone can be on any network; older Glassly App builds need the same Wi-Fi.
55
57
 
56
58
  Both `dev` and `release` take the same QR flags. `--qr` / `-q` sizes the terminal QR (`small|medium|large`, or `sm|md|lg`; default `medium`). `--qr-output <path>` also writes a PNG. Without it the CLI still writes a PNG to a temp path and deletes it on exit; pass `--qr-output` when you want to keep the file.
57
59
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glassly/miniapp-cli",
3
- "version": "0.1.9",
3
+ "version": "0.1.10-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": {
@@ -18,6 +18,7 @@
18
18
  },
19
19
  "dependencies": {
20
20
  "@clack/prompts": "^1.9.0",
21
+ "@number0/iroh": "^1.2.0",
21
22
  "jszip": "^3.10.2",
22
23
  "qrcode": "^1.5.4",
23
24
  "typescript": "^6.0.3"
@@ -0,0 +1,107 @@
1
+ import {afterAll, beforeAll, describe, expect, test} from 'bun:test';
2
+ import {mkdtempSync, rmSync, statSync} from 'fs';
3
+ import os from 'os';
4
+ import {join} from 'path';
5
+ import {Endpoint, EndpointTicket} from '@number0/iroh';
6
+ import {
7
+ DEV_TUNNEL_ALPN,
8
+ TARGET_DEV,
9
+ TARGET_HTTP,
10
+ identityPath,
11
+ loadOrCreateIdentity,
12
+ startDevTunnel,
13
+ tokenMatches,
14
+ type DevTunnel,
15
+ } from './dev-tunnel';
16
+
17
+ const ALPN = Array.from(Buffer.from(DEV_TUNNEL_ALPN));
18
+
19
+ function header(target: number, token: string): number[] {
20
+ const bytes = Array.from(Buffer.from(token));
21
+ return [target, bytes.length, ...bytes];
22
+ }
23
+
24
+ describe('identity', () => {
25
+ const dir = mkdtempSync(join(os.tmpdir(), 'dev-tunnel-id-'));
26
+ afterAll(() => rmSync(dir, {recursive: true, force: true}));
27
+
28
+ test('persists one private identity per package', () => {
29
+ const path = identityPath('com.example.app', dir);
30
+ const key = () => Array.from({length: 32}, (_, i) => i);
31
+ const first = loadOrCreateIdentity(path, key);
32
+ const second = loadOrCreateIdentity(path, () => Array(32).fill(9));
33
+ expect(second).toEqual(first);
34
+ expect(first.secretKey).toBe(Buffer.from(key()).toString('hex'));
35
+ expect(first.token.length).toBeGreaterThanOrEqual(20);
36
+ expect(statSync(path).mode & 0o777).toBe(0o600);
37
+ });
38
+
39
+ test('keeps package names from escaping the directory', () => {
40
+ expect(identityPath('../../etc/passwd', dir)).toBe(join(dir, '.._.._etc_passwd.json'));
41
+ });
42
+
43
+ test('compares tokens exactly', () => {
44
+ expect(tokenMatches(Array.from(Buffer.from('abc')), 'abc')).toBe(true);
45
+ expect(tokenMatches(Array.from(Buffer.from('abd')), 'abc')).toBe(false);
46
+ expect(tokenMatches(Array.from(Buffer.from('ab')), 'abc')).toBe(false);
47
+ });
48
+ });
49
+
50
+ describe('startDevTunnel', () => {
51
+ const dir = mkdtempSync(join(os.tmpdir(), 'dev-tunnel-e2e-'));
52
+ let http: ReturnType<typeof Bun.serve>;
53
+ let dev: ReturnType<typeof Bun.serve>;
54
+ let tunnel: DevTunnel;
55
+ let client: Endpoint;
56
+
57
+ beforeAll(async () => {
58
+ http = Bun.serve({port: 0, hostname: '127.0.0.1', fetch: (req) => new Response(`http ${new URL(req.url).pathname}`)});
59
+ dev = Bun.serve({port: 0, hostname: '127.0.0.1', fetch: () => new Response('dev sidecar')});
60
+ const started = await startDevTunnel({
61
+ packageName: 'com.example.tunnel',
62
+ httpPort: http.port!,
63
+ devPort: dev.port!,
64
+ identityDir: dir,
65
+ log: () => {},
66
+ });
67
+ if (!started) throw new Error('iroh unavailable on this machine');
68
+ tunnel = started;
69
+ client = await Endpoint.bind({});
70
+ });
71
+
72
+ afterAll(async () => {
73
+ await client?.close();
74
+ await tunnel?.close();
75
+ http?.stop(true);
76
+ dev?.stop(true);
77
+ rmSync(dir, {recursive: true, force: true});
78
+ });
79
+
80
+ async function request(target: number, token: string, path: string): Promise<string> {
81
+ const conn = await client.connect(EndpointTicket.fromString(tunnel.ticket()).endpointAddr(), ALPN);
82
+ const bi = await conn.openBi();
83
+ await bi.send.writeAll([...header(target, token), ...Array.from(Buffer.from(`GET ${path} HTTP/1.0\r\nHost: x\r\n\r\n`))]);
84
+ await bi.send.finish();
85
+ return Buffer.from(await bi.recv.readToEnd(1024 * 1024)).toString();
86
+ }
87
+
88
+ test('routes each target to its local server', async () => {
89
+ expect(await request(TARGET_HTTP, tunnel.token, '/miniapp.json')).toContain('http /miniapp.json');
90
+ expect(await request(TARGET_DEV, tunnel.token, '/__host_dev/health')).toContain('dev sidecar');
91
+ }, 20_000);
92
+
93
+ test('rejects a stream with the wrong token', async () => {
94
+ const response = await request(TARGET_HTTP, 'not-the-token', '/miniapp.json').catch(() => '');
95
+ expect(response).toBe('');
96
+ }, 20_000);
97
+
98
+ test('keeps the endpoint id across restarts', async () => {
99
+ const again = await startDevTunnel({packageName: 'com.example.tunnel', httpPort: http.port!, devPort: null, identityDir: dir, log: () => {}});
100
+ try {
101
+ expect(again?.endpointId).toBe(tunnel.endpointId);
102
+ expect(again?.token).toBe(tunnel.token);
103
+ } finally {
104
+ await again?.close();
105
+ }
106
+ }, 20_000);
107
+ });
@@ -0,0 +1,213 @@
1
+ import {randomBytes, timingSafeEqual} from 'crypto';
2
+ import {once} from 'events';
3
+ import {chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync} from 'fs';
4
+ import net from 'net';
5
+ import os from 'os';
6
+ import {join} from 'path';
7
+ import type {BiStream, Connection, Endpoint, RecvStream, SendStream} from '@number0/iroh';
8
+
9
+ // Wire protocol shared with mobile/modules/dev-tunnel/rust/src/tunnel.rs: every
10
+ // bi-stream opens with [target, tokenLength, ...token], then carries raw TCP bytes.
11
+ export const DEV_TUNNEL_ALPN = 'glassly/dev-tunnel/1';
12
+ export const TARGET_HTTP = 0;
13
+ export const TARGET_DEV = 1;
14
+
15
+ const ONLINE_TIMEOUT_MS = 5_000;
16
+ const READ_CHUNK_BYTES = 64 * 1024;
17
+
18
+ export interface DevTunnelIdentity {
19
+ secretKey: string;
20
+ token: string;
21
+ }
22
+
23
+ export interface DevTunnel {
24
+ endpointId: string;
25
+ token: string;
26
+ ticket(): string;
27
+ close(): Promise<void>;
28
+ }
29
+
30
+ export interface DevTunnelOptions {
31
+ packageName: string;
32
+ httpPort: number;
33
+ devPort: number | null;
34
+ identityDir?: string;
35
+ log?: (line: string) => void;
36
+ }
37
+
38
+ export function defaultIdentityDir(): string {
39
+ return join(os.homedir(), '.glassly', 'dev-tunnel');
40
+ }
41
+
42
+ export function identityPath(packageName: string, dir = defaultIdentityDir()): string {
43
+ return join(dir, `${packageName.replace(/[^A-Za-z0-9._-]/g, '_')}.json`);
44
+ }
45
+
46
+ // One key per package keeps the endpoint id stable across `glassly dev`
47
+ // restarts, so the phone's saved dev entry reconnects without a re-scan.
48
+ export function loadOrCreateIdentity(path: string, generateSecretKey: () => number[]): DevTunnelIdentity {
49
+ if (existsSync(path)) {
50
+ try {
51
+ const parsed = JSON.parse(readFileSync(path, 'utf-8')) as Partial<DevTunnelIdentity>;
52
+ if (typeof parsed.secretKey === 'string' && /^[0-9a-f]{64}$/.test(parsed.secretKey) && typeof parsed.token === 'string' && parsed.token) {
53
+ return {secretKey: parsed.secretKey, token: parsed.token};
54
+ }
55
+ } catch {
56
+ // fall through and mint a fresh identity
57
+ }
58
+ }
59
+ const identity: DevTunnelIdentity = {
60
+ secretKey: Buffer.from(generateSecretKey()).toString('hex'),
61
+ token: randomBytes(16).toString('base64url'),
62
+ };
63
+ mkdirSync(join(path, '..'), {recursive: true, mode: 0o700});
64
+ writeFileSync(path, JSON.stringify(identity, null, 2) + '\n', {mode: 0o600});
65
+ chmodSync(path, 0o600);
66
+ return identity;
67
+ }
68
+
69
+ export function tokenMatches(presented: number[], expected: string): boolean {
70
+ const want = Buffer.from(expected);
71
+ const got = Buffer.from(presented);
72
+ return got.length === want.length && timingSafeEqual(got, want);
73
+ }
74
+
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
+ async function handleStream(bi: BiStream, token: string, ports: Record<number, number | null>): Promise<void> {
117
+ const {send, recv} = bi;
118
+ try {
119
+ const [target, tokenLength] = await recv.readExact(2);
120
+ const presented = tokenLength > 0 ? await recv.readExact(tokenLength) : [];
121
+ const port = ports[target];
122
+ if (!tokenMatches(presented, token) || !port) {
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)]);
131
+ } catch {
132
+ await send.reset(0n).catch(() => {});
133
+ }
134
+ }
135
+
136
+ // The phone redials on every launch, so only log a phone's first live connection.
137
+ const liveConnections = new Map<string, number>();
138
+
139
+ async function handleConnection(conn: Connection, token: string, ports: Record<number, number | null>, log: (line: string) => void) {
140
+ const remote = conn.remoteId().toString();
141
+ const live = liveConnections.get(remote) ?? 0;
142
+ liveConnections.set(remote, live + 1);
143
+ if (live === 0) log(`📶 Phone connected over iroh (${describePath(conn)})`);
144
+ void conn.closed().catch(() => {}).finally(() => {
145
+ const left = (liveConnections.get(remote) ?? 1) - 1;
146
+ if (left > 0) liveConnections.set(remote, left);
147
+ else liveConnections.delete(remote);
148
+ });
149
+ for (;;) {
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
+ }
173
+ }
174
+
175
+ /**
176
+ * Bind an iroh endpoint that splices each authenticated phone stream onto the
177
+ * local dev server or sidecar. Returns null (after logging why) when iroh is
178
+ * unavailable on this machine, so `glassly dev` falls back to the LAN QR.
179
+ */
180
+ export async function startDevTunnel(options: DevTunnelOptions): Promise<DevTunnel | null> {
181
+ const log = options.log ?? ((line: string) => console.log(line));
182
+ const iroh = await loadIroh();
183
+ if (typeof iroh === 'string') {
184
+ log(`iroh tunnel disabled: ${iroh}. The QR only carries the LAN URL.`);
185
+ return null;
186
+ }
187
+
188
+ const identity = loadOrCreateIdentity(identityPath(options.packageName, options.identityDir), () =>
189
+ iroh.SecretKey.generate().toBytes(),
190
+ );
191
+ let endpoint: Endpoint;
192
+ try {
193
+ endpoint = await iroh.Endpoint.bind({
194
+ secretKey: Array.from(Buffer.from(identity.secretKey, 'hex')),
195
+ alpns: [Array.from(Buffer.from(DEV_TUNNEL_ALPN))],
196
+ });
197
+ } catch (error) {
198
+ log(`iroh tunnel disabled: ${(error as Error).message}. The QR only carries the LAN URL.`);
199
+ return null;
200
+ }
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
+
204
+ const ports = {[TARGET_HTTP]: options.httpPort, [TARGET_DEV]: options.devPort};
205
+ void acceptLoop(endpoint, identity.token, ports, log);
206
+
207
+ return {
208
+ endpointId: endpoint.id().toString(),
209
+ token: identity.token,
210
+ ticket: () => iroh.EndpointTicket.fromAddr(endpoint.addr()).toString(),
211
+ close: () => endpoint.close(),
212
+ };
213
+ }
package/src/dev.ts CHANGED
@@ -5,6 +5,7 @@ import { printQR, writeQRPng, type QRSize } from './qr.js';
5
5
  import { validateManifest } from './manifest.js';
6
6
  import { startDevSidecar } from './dev-server.js';
7
7
  import { getLanIp, getMdnsHostname } from './lan.js';
8
+ import { startDevTunnel } from './dev-tunnel.js';
8
9
 
9
10
  const DEFAULT_DEV_PORT = 3000;
10
11
  const DEV_PORT_SCAN_LIMIT = 50;
@@ -21,6 +22,7 @@ export interface DevOptions {
21
22
  qrOutput?: string;
22
23
  /** Terminal QR size (--qr/-q small|medium|large). Defaults to medium. */
23
24
  qrSize?: QRSize;
25
+ iroh?: boolean;
24
26
  signDevAttestation?: (
25
27
  input: DevAttestationInput,
26
28
  ) => string | Promise<string | null | undefined> | null | undefined;
@@ -224,6 +226,9 @@ export async function dev(options: DevOptions = {}): Promise<void> {
224
226
  }
225
227
 
226
228
  const mdnsHost = getMdnsHostname();
229
+ const tunnel = options.iroh === false
230
+ ? null
231
+ : await startDevTunnel({ packageName, httpPort: port, devPort: sidecarPort });
227
232
 
228
233
  const buildDevUrl = async (ip: string): Promise<string> => {
229
234
  const devServerUrl = `http://${ip}:${port}`;
@@ -232,15 +237,19 @@ export async function dev(options: DevOptions = {}): Promise<void> {
232
237
  // mDNS hint lets the phone retry via ComputerName.local when the raw IP
233
238
  // goes stale after a Wi-Fi/DHCP change — same QR, new address under the hood.
234
239
  const withMdns = mdnsHost ? `${withDevPort}&mdns=${encodeURIComponent(mdnsHost)}` : withDevPort;
235
- if (!options.signDevAttestation) return withMdns;
240
+ // Older Glassly App builds ignore `iroh`/`token` and keep using `url`.
241
+ const withIroh = tunnel
242
+ ? `${withMdns}&iroh=${encodeURIComponent(tunnel.ticket())}&token=${encodeURIComponent(tunnel.token)}`
243
+ : withMdns;
244
+ if (!options.signDevAttestation) return withIroh;
236
245
 
237
246
  try {
238
247
  const attestation = await options.signDevAttestation({ packageName, devServerUrl });
239
- if (!attestation) return withMdns;
240
- return `${withMdns}&attestation=${encodeURIComponent(attestation)}`;
248
+ if (!attestation) return withIroh;
249
+ return `${withIroh}&attestation=${encodeURIComponent(attestation)}`;
241
250
  } catch (error) {
242
251
  console.warn(`Warning: could not sign dev URL (${(error as Error).message}). Miniapp auto-auth will be unavailable.`);
243
- return withMdns;
252
+ return withIroh;
244
253
  }
245
254
  };
246
255
 
@@ -253,7 +262,12 @@ export async function dev(options: DevOptions = {}): Promise<void> {
253
262
  console.log('║ 3. Under "Mini App Development", tap ║');
254
263
  console.log('║ "Scan Mini App QR Code" and scan the QR below ║');
255
264
  console.log('║ ║');
256
- console.log('║ Your phone must be on the same Wi-Fi as this computer. ║');
265
+ if (tunnel) {
266
+ console.log('║ Your phone can be on any network (connects over iroh). ║');
267
+ console.log('║ Older Glassly App builds still need the same Wi-Fi. ║');
268
+ } else {
269
+ console.log('║ Your phone must be on the same Wi-Fi as this computer. ║');
270
+ }
257
271
  console.log('║ ║');
258
272
  console.log('║ Dev mode is live and temporary: ║');
259
273
  console.log('║ • Keep this process and computer running. ║');
@@ -281,6 +295,9 @@ export async function dev(options: DevOptions = {}): Promise<void> {
281
295
  };
282
296
 
283
297
  printBanner();
298
+ if (tunnel) {
299
+ console.log(`iroh: ${tunnel.endpointId.slice(0, 10)}… (same id every run, so a saved dev miniapp reconnects without a re-scan)`);
300
+ }
284
301
  if (mdnsHost) {
285
302
  console.log(`mDNS: ${mdnsHost} (phone can keep using this name across Wi-Fi IP changes)\n`);
286
303
  }
@@ -336,7 +353,8 @@ export async function dev(options: DevOptions = {}): Promise<void> {
336
353
  }
337
354
  sidecar?.stop();
338
355
  userServer.stop(true);
339
- process.exit(0);
356
+ const closing = tunnel ? tunnel.close().catch(() => {}) : Promise.resolve();
357
+ void Promise.race([closing, new Promise((r) => setTimeout(r, 1_000))]).then(() => process.exit(0));
340
358
  };
341
359
  process.on('SIGINT', shutdown);
342
360
  process.on('SIGTERM', shutdown);