@glassly/miniapp-cli 0.1.17 → 0.1.18-beta.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,113 @@
1
+ /**
2
+ * `glassly link` state: one JSON file in ~/.glassly/link/ (directory 0700, file 0600) holding the
3
+ * iroh secret key that keeps this computer's endpoint id across restarts, the linked phones and the
4
+ * gterm address and token.
5
+ */
6
+ import {chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync} from 'fs';
7
+ import {homedir, hostname} from 'os';
8
+ import {join} from 'path';
9
+
10
+ const DEFAULT_GTERM_URL = 'ws://127.0.0.1:8737';
11
+
12
+ export interface LinkedPhone {
13
+ id: string;
14
+ name: string;
15
+ secret: string;
16
+ linkedAt: string;
17
+ }
18
+
19
+ export interface LinkState {
20
+ version: 2;
21
+ name: string;
22
+ secretKey: string;
23
+ phones: LinkedPhone[];
24
+ gterm: {url: string; token?: string};
25
+ }
26
+
27
+ export function linkHome(home = homedir()): string {
28
+ return join(home, '.glassly', 'link');
29
+ }
30
+
31
+ export function statePath(dir: string): string {
32
+ return join(dir, 'state.json');
33
+ }
34
+
35
+ function computerName(): string {
36
+ return hostname().replace(/\.local$/, '');
37
+ }
38
+
39
+ function isState(value: unknown): value is LinkState {
40
+ const state = value as Partial<LinkState> | null;
41
+ return (
42
+ typeof state === 'object' &&
43
+ state !== null &&
44
+ state.version === 2 &&
45
+ typeof state.name === 'string' &&
46
+ typeof state.secretKey === 'string' &&
47
+ /^[0-9a-f]{64}$/.test(state.secretKey) &&
48
+ Array.isArray(state.phones) &&
49
+ typeof state.gterm?.url === 'string'
50
+ );
51
+ }
52
+
53
+ export function loadState(dir: string): LinkState | null {
54
+ const path = statePath(dir);
55
+ if (!existsSync(path)) return null;
56
+ const value: unknown = JSON.parse(readFileSync(path, 'utf8'));
57
+ if (!isState(value)) {
58
+ throw new Error(`${path} isn't a glassly link state file this version reads. Move it away, then run \`glassly link\` to link again.`);
59
+ }
60
+ return value;
61
+ }
62
+
63
+ export function loadOrCreateState(dir: string, generateSecretKey: () => number[], name = computerName()): LinkState {
64
+ const existing = loadState(dir);
65
+ if (existing) return existing;
66
+ const state: LinkState = {
67
+ version: 2,
68
+ name,
69
+ secretKey: Buffer.from(generateSecretKey()).toString('hex'),
70
+ phones: [],
71
+ gterm: {url: DEFAULT_GTERM_URL},
72
+ };
73
+ saveState(dir, state);
74
+ return state;
75
+ }
76
+
77
+ export function saveState(dir: string, state: LinkState): void {
78
+ mkdirSync(dir, {recursive: true, mode: 0o700});
79
+ chmodSync(dir, 0o700);
80
+ const path = statePath(dir);
81
+ const temp = `${path}.${process.pid}.tmp`;
82
+ writeFileSync(temp, `${JSON.stringify(state, null, 2)}\n`, {mode: 0o600});
83
+ chmodSync(temp, 0o600);
84
+ renameSync(temp, path);
85
+ }
86
+
87
+ export function updateState(dir: string, change: (state: LinkState) => void): LinkState {
88
+ const state = loadState(dir);
89
+ if (!state) throw new Error('This computer is not set up for linking. Run `glassly link` first.');
90
+ change(state);
91
+ saveState(dir, state);
92
+ return state;
93
+ }
94
+
95
+ export type UnpairResult =
96
+ | {status: 'removed'; phone: LinkedPhone}
97
+ | {status: 'ambiguous'; matches: LinkedPhone[]}
98
+ | {status: 'not-found'};
99
+
100
+ /** Removes the phone with this id, or the only phone with this name. */
101
+ export function unpairPhone(dir: string, nameOrId: string): UnpairResult {
102
+ const state = loadState(dir);
103
+ if (!state) return {status: 'not-found'};
104
+ const byId = state.phones.find(phone => phone.id === nameOrId);
105
+ const matches = byId ? [byId] : state.phones.filter(phone => phone.name === nameOrId);
106
+ if (matches.length === 0) return {status: 'not-found'};
107
+ if (matches.length > 1) return {status: 'ambiguous', matches};
108
+ const phone = matches[0];
109
+ updateState(dir, current => {
110
+ current.phones = current.phones.filter(entry => entry.id !== phone.id);
111
+ });
112
+ return {status: 'removed', phone};
113
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The service's WebSocket upgrade as it arrives over a route: the phone token rides in the request
3
+ * target (`?link=`), and gterm-server gets the same request with its target rewritten to `/`, so the
4
+ * credential never reaches it. A head that is too long, too slow or not HTTP carries no credential.
5
+ */
6
+ import http from 'http';
7
+ import type {BiStream, RecvStream} from '@number0/iroh';
8
+ import {LINK_REFUSAL_STATUS, LINK_SERVICE_PARAM, type LinkRefusal} from '@glassly/miniapp/link';
9
+
10
+ const MAX_HEAD_BYTES = 8 * 1024;
11
+ const HEAD_TIMEOUT_MS = 5_000;
12
+ const CRLF = Buffer.from('\r\n');
13
+ const HEAD_END = Buffer.from('\r\n\r\n');
14
+
15
+ interface ServiceUpgrade {
16
+ credential: string | null;
17
+ forwarded: Buffer;
18
+ }
19
+
20
+ function parseUpgrade(bytes: Buffer): ServiceUpgrade | null {
21
+ const lineEnd = bytes.indexOf(CRLF);
22
+ const request = /^(\S+) (\S+) (HTTP\/1\.[01])$/.exec(bytes.subarray(0, lineEnd).toString('latin1'));
23
+ if (!request) return null;
24
+ const [, method, target, version] = request;
25
+ const query = target.includes('?') ? target.slice(target.indexOf('?') + 1) : '';
26
+ return {
27
+ credential: new URLSearchParams(query).get(LINK_SERVICE_PARAM),
28
+ forwarded: Buffer.concat([Buffer.from(`${method} / ${version}`, 'latin1'), bytes.subarray(lineEnd)]),
29
+ };
30
+ }
31
+
32
+ async function readHead(recv: RecvStream): Promise<ServiceUpgrade | null> {
33
+ let bytes = Buffer.alloc(0);
34
+ while (bytes.length < MAX_HEAD_BYTES) {
35
+ const chunk = await recv.read(MAX_HEAD_BYTES - bytes.length);
36
+ if (chunk.length === 0) return null;
37
+ bytes = Buffer.concat([bytes, Buffer.from(chunk)]);
38
+ if (bytes.includes(HEAD_END)) return parseUpgrade(bytes);
39
+ }
40
+ return null;
41
+ }
42
+
43
+ export async function readUpgrade(recv: RecvStream): Promise<ServiceUpgrade | null> {
44
+ let timer: ReturnType<typeof setTimeout> | undefined;
45
+ const timeout = new Promise<null>(resolve => (timer = setTimeout(() => resolve(null), HEAD_TIMEOUT_MS)));
46
+ try {
47
+ return await Promise.race([readHead(recv).catch(() => null), timeout]);
48
+ } finally {
49
+ clearTimeout(timer);
50
+ }
51
+ }
52
+
53
+ export async function refuseUpgrade(bi: BiStream, error: LinkRefusal): Promise<void> {
54
+ const status = LINK_REFUSAL_STATUS[error];
55
+ const body = JSON.stringify({error});
56
+ const response =
57
+ `HTTP/1.1 ${status} ${http.STATUS_CODES[status]}\r\ncontent-type: application/json\r\n` +
58
+ `content-length: ${Buffer.byteLength(body)}\r\nconnection: close\r\n\r\n${body}`;
59
+ try {
60
+ await bi.send.writeAll(Array.from(Buffer.from(response)));
61
+ await bi.send.finish();
62
+ } catch {
63
+ await bi.send.reset(0n).catch(() => {});
64
+ }
65
+ await bi.recv.stop(0n).catch(() => {});
66
+ }
@@ -2,12 +2,20 @@ import {AUDIO_MESSAGES, handleAudio} from "./audio.js"
2
2
  import {BLOB_MESSAGES, handleBlobs} from "./blobs.js"
3
3
  import type {SimTypeHandler} from "./context.js"
4
4
  import {HARDWARE_MESSAGES, handleHardware} from "./hardware.js"
5
+ import {handleLink} from "./link.js"
5
6
  import {NAVIGATION_MESSAGES, handleNavigation} from "./navigation.js"
6
7
  import {SERVICE_MESSAGES, handleServices} from "./services.js"
7
8
 
8
9
  export type {SimTypeContext, SimTypeHandler} from "./context.js"
9
10
 
10
- export const TYPE_HANDLERS: SimTypeHandler[] = [handleBlobs, handleServices, handleNavigation, handleHardware, handleAudio]
11
+ export const TYPE_HANDLERS: SimTypeHandler[] = [
12
+ handleBlobs,
13
+ handleServices,
14
+ handleNavigation,
15
+ handleHardware,
16
+ handleAudio,
17
+ handleLink,
18
+ ]
11
19
  export const FORCED_MESSAGES: Record<string, string> = {
12
20
  ...BLOB_MESSAGES,
13
21
  ...SERVICE_MESSAGES,
@@ -0,0 +1,45 @@
1
+ import {readLinkOpen} from "@glassly/miniapp/host"
2
+ import {MiniappErrorCode, MiniappRequestType} from "@glassly/miniapp/protocol"
3
+
4
+ import {dialTunnel, loadIroh, type DialedTunnel} from "../../iroh-tunnel.js"
5
+ import type {SimTypeContext, SimTypeHandler} from "./context.js"
6
+
7
+ const sessions = new WeakMap<SimTypeContext, Map<string, Promise<DialedTunnel>>>()
8
+
9
+ // Like the Glassly App's tunnel: one per ticket, with no stream token, kept for the session.
10
+ function tunnelsFor(ctx: SimTypeContext): Map<string, Promise<DialedTunnel>> {
11
+ let tunnels = sessions.get(ctx)
12
+ if (!tunnels) {
13
+ const created = new Map<string, Promise<DialedTunnel>>()
14
+ sessions.set(ctx, created)
15
+ ctx.onEnd(() => created.forEach((tunnel) => void tunnel.then((open) => open.close()).catch(() => {})))
16
+ tunnels = created
17
+ }
18
+ return tunnels
19
+ }
20
+
21
+ async function linkOpen(ctx: SimTypeContext, payload: Record<string, unknown>, requestId?: string): Promise<void> {
22
+ const request = readLinkOpen(payload)
23
+ if (!request.ok) return ctx.fail(requestId, request.code, request.message)
24
+ const iroh = await loadIroh()
25
+ if (typeof iroh === "string") {
26
+ return ctx.fail(requestId, MiniappErrorCode.NOT_IMPLEMENTED, `glassly sim can't open computer links here: ${iroh}.`)
27
+ }
28
+ const tunnels = tunnelsFor(ctx)
29
+ const tunnel = tunnels.get(request.ticket) ?? dialTunnel({ticket: request.ticket, token: ""})
30
+ tunnels.set(request.ticket, tunnel)
31
+ try {
32
+ const {endpointId, ports} = await tunnel
33
+ ctx.log("info", `Linked to ${endpointId.slice(0, 10)}… over iroh on 127.0.0.1:${ports[0]} and ${ports[1]}`)
34
+ ctx.reply(requestId, true, {endpointId, host: "127.0.0.1", controlPort: ports[0], servicePort: ports[1]})
35
+ } catch (error) {
36
+ if (tunnels.get(request.ticket) === tunnel) tunnels.delete(request.ticket)
37
+ ctx.fail(requestId, MiniappErrorCode.LINK_UNREACHABLE, error instanceof Error ? error.message : String(error))
38
+ }
39
+ }
40
+
41
+ export const handleLink: SimTypeHandler = (ctx, type, payload, requestId) => {
42
+ if (type !== MiniappRequestType.LINK_OPEN) return false
43
+ void linkOpen(ctx, payload, requestId)
44
+ return true
45
+ }