@stav-ai/cli 0.1.7 → 0.1.9
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 +13 -5
- package/dist/adapters/index.js +61 -20
- package/dist/adapters/pi-stav-provider.js +2 -1
- package/dist/agent/index.js +626 -0
- package/dist/agent/pairings.js +83 -0
- package/dist/agent/passkey.js +86 -0
- package/dist/agent/questions.js +232 -0
- package/dist/agent/relay.js +224 -0
- package/dist/agent/steps.js +131 -0
- package/dist/agent/wire.js +41 -0
- package/dist/cli.js +27 -3
- package/dist/config.js +1 -0
- package/dist/http.js +2 -1
- package/dist/launch.js +21 -5
- package/dist/noise.js +225 -0
- package/dist/prompt.js +119 -0
- package/dist/stav.js +3 -3
- package/dist/store/index.js +10 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agents this computer is paired with, where the sign-in is kept. One
|
|
3
|
+
* entry for each API host and agent, small enough for a keychain, and an
|
|
4
|
+
* index of the agent ids: `stav agent forget <name>` must work also when Stav
|
|
5
|
+
* lists no agents.
|
|
6
|
+
*
|
|
7
|
+
* An entry that cannot be read is an error, never "not paired": pairing again
|
|
8
|
+
* would leave the old computer on both lists.
|
|
9
|
+
*/
|
|
10
|
+
import { StavError } from '../errors.js';
|
|
11
|
+
import { FileStore } from '../store/index.js';
|
|
12
|
+
import { decode } from './wire.js';
|
|
13
|
+
function parse(raw, agentId) {
|
|
14
|
+
let p = null;
|
|
15
|
+
try {
|
|
16
|
+
p = JSON.parse(raw);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
const text = (v) => typeof v === 'string' && v !== '';
|
|
22
|
+
const ok = p && p.v === 1 && p.agent_id === agentId && [p.team_id, p.user_id, p.slug, p.name, p.computer].every(text)
|
|
23
|
+
&& (p.device_id === undefined || text(p.device_id)) && typeof p.can_answer === 'boolean'
|
|
24
|
+
&& decode(p.private_key, 'base64', 32) && decode(p.connector_key, 'base64', 32) && decode(p.passkey_id, 'base64url');
|
|
25
|
+
return ok ? p : null;
|
|
26
|
+
}
|
|
27
|
+
export class Pairings {
|
|
28
|
+
store;
|
|
29
|
+
prefix;
|
|
30
|
+
constructor(store, cfg) {
|
|
31
|
+
this.store = store;
|
|
32
|
+
this.prefix = `agent:${new URL(cfg.apiUrl).host}`;
|
|
33
|
+
}
|
|
34
|
+
/** A damaged file would make every pairing look missing. */
|
|
35
|
+
async check() {
|
|
36
|
+
if (this.store instanceof FileStore && (await this.store.damaged())) {
|
|
37
|
+
throw new StavError(`${this.store.file} cannot be read, and the paired computers are in it. Repair it, or move it away and pair again.`, 'store_damaged');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async ids() {
|
|
41
|
+
const raw = await this.store.get(this.prefix);
|
|
42
|
+
if (raw === null)
|
|
43
|
+
return [];
|
|
44
|
+
try {
|
|
45
|
+
const list = JSON.parse(raw);
|
|
46
|
+
if (Array.isArray(list) && list.every((x) => typeof x === 'string'))
|
|
47
|
+
return list;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// Said below.
|
|
51
|
+
}
|
|
52
|
+
throw new StavError('The list of paired agents stored on this computer cannot be read. Run stav agent forget with the id of the agent.', 'pairing_damaged');
|
|
53
|
+
}
|
|
54
|
+
/** A list that cannot be read starts again: each pairing is still found by its agent's id. */
|
|
55
|
+
async writeIds(change) {
|
|
56
|
+
await this.store.set(this.prefix, JSON.stringify(change(await this.ids().catch(() => []))));
|
|
57
|
+
}
|
|
58
|
+
/** The pairing with one agent, null when there is none. */
|
|
59
|
+
async get(agentId) {
|
|
60
|
+
const raw = await this.store.get(`${this.prefix}:${agentId}`);
|
|
61
|
+
const p = raw === null ? null : parse(raw, agentId);
|
|
62
|
+
if (p || (raw === null && !(await this.ids()).includes(agentId)))
|
|
63
|
+
return p;
|
|
64
|
+
throw new StavError(`The pairing with agent ${agentId} stored on this computer cannot be read. Run stav agent forget ${agentId}, then pair again.`, 'pairing_damaged');
|
|
65
|
+
}
|
|
66
|
+
async save(p) {
|
|
67
|
+
await this.store.set(`${this.prefix}:${p.agent_id}`, JSON.stringify(p));
|
|
68
|
+
await this.writeIds((ids) => [...ids.filter((id) => id !== p.agent_id), p.agent_id]);
|
|
69
|
+
}
|
|
70
|
+
async remove(agentId) {
|
|
71
|
+
await this.store.delete(`${this.prefix}:${agentId}`);
|
|
72
|
+
await this.writeIds((ids) => ids.filter((id) => id !== agentId));
|
|
73
|
+
}
|
|
74
|
+
/** The ids of every paired agent, with the pairing, or null when it cannot be read. */
|
|
75
|
+
async all() {
|
|
76
|
+
const out = [];
|
|
77
|
+
for (const id of await this.ids()) {
|
|
78
|
+
const raw = await this.store.get(`${this.prefix}:${id}`);
|
|
79
|
+
out.push({ id, pairing: raw === null ? null : parse(raw, id) });
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The passkey page (WATCH.md § 4): the CLI opens it in the browser and gets
|
|
3
|
+
* the answer back on 127.0.0.1. Everything the page needs is after `#`, so it
|
|
4
|
+
* never reaches Stav.
|
|
5
|
+
*/
|
|
6
|
+
import http from 'node:http';
|
|
7
|
+
import { newState } from '../auth/pkce.js';
|
|
8
|
+
import { StavError } from '../errors.js';
|
|
9
|
+
import { decode } from './wire.js';
|
|
10
|
+
const PASSKEY_ALGS = [-7, -8, -257];
|
|
11
|
+
/** The fields of this mode and nothing else, or null. The connector checks what they say. */
|
|
12
|
+
function readAnswer(mode, raw) {
|
|
13
|
+
let o;
|
|
14
|
+
try {
|
|
15
|
+
o = JSON.parse((decode(raw, 'base64url') ?? '').toString());
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
const text = (name) => (decode(o?.[name], 'base64url') ? o[name] : null);
|
|
21
|
+
const [id, client_data, auth_data] = ['id', 'client_data', 'auth_data'].map(text);
|
|
22
|
+
if (!id || !client_data || !auth_data)
|
|
23
|
+
return null;
|
|
24
|
+
if (mode === 'pair') {
|
|
25
|
+
const public_key = text('public_key');
|
|
26
|
+
return public_key && PASSKEY_ALGS.includes(o.alg) ? { id, alg: o.alg, public_key, client_data, auth_data } : null;
|
|
27
|
+
}
|
|
28
|
+
const signature = text('signature');
|
|
29
|
+
return signature ? { id, client_data, auth_data, signature } : null;
|
|
30
|
+
}
|
|
31
|
+
const PAGE = (text) => `<!doctype html><meta charset="utf-8"><title>Stav CLI</title><body style="font-family:system-ui;margin:4rem"><h1>${text}</h1><p>You can close this tab and go back to the terminal.</p></body>`;
|
|
32
|
+
export async function passkeyPage(o) {
|
|
33
|
+
const state = newState();
|
|
34
|
+
let resolve;
|
|
35
|
+
let reject;
|
|
36
|
+
const answer = new Promise((res, rej) => {
|
|
37
|
+
resolve = res;
|
|
38
|
+
reject = rej;
|
|
39
|
+
});
|
|
40
|
+
answer.catch(() => undefined); // It may end while nobody waits for it yet.
|
|
41
|
+
let used = false;
|
|
42
|
+
const server = http.createServer((req, res) => {
|
|
43
|
+
const [path, query = ''] = (req.url ?? '').split('?', 2);
|
|
44
|
+
const params = new URLSearchParams(query);
|
|
45
|
+
const error = params.get('error');
|
|
46
|
+
const got = readAnswer(o.mode, params.get('answer'));
|
|
47
|
+
// Anything else, such as a stray tab or a page that guesses the port, is ignored.
|
|
48
|
+
if (used || req.method !== 'GET' || path !== '/passkey' || params.get('state') !== state
|
|
49
|
+
|| !(got || error === 'cancelled' || error === 'failed')) {
|
|
50
|
+
res.writeHead(404, { Connection: 'close' }).end();
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
used = true;
|
|
54
|
+
res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', Connection: 'close' });
|
|
55
|
+
res.end(PAGE(got ? 'The terminal has the answer' : 'The passkey was not used'));
|
|
56
|
+
if (got)
|
|
57
|
+
resolve(got);
|
|
58
|
+
else if (error === 'cancelled')
|
|
59
|
+
reject(new StavError('Cancelled in the browser.', 'cancelled'));
|
|
60
|
+
else
|
|
61
|
+
reject(new StavError('The browser could not use a passkey. Try another browser, or another place to keep passkeys.', 'passkey_failed'));
|
|
62
|
+
});
|
|
63
|
+
await new Promise((ok, bad) => {
|
|
64
|
+
server.once('error', bad);
|
|
65
|
+
server.listen(0, '127.0.0.1', ok);
|
|
66
|
+
});
|
|
67
|
+
const timer = setTimeout(() => reject(new StavError('Nothing came back from the browser in time. Run the command again.', 'timeout')), o.timeoutMs);
|
|
68
|
+
const onAbort = () => reject(o.signal.reason);
|
|
69
|
+
if (o.signal.aborted)
|
|
70
|
+
onAbort();
|
|
71
|
+
else
|
|
72
|
+
o.signal.addEventListener('abort', onAbort, { once: true });
|
|
73
|
+
const fragment = {
|
|
74
|
+
v: 1, mode: o.mode, h: o.h.toString('base64url'), port: server.address().port, state, agent: o.agent,
|
|
75
|
+
...(o.mode === 'pair' ? { computer: o.computer } : { id: o.id }),
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
url: `${o.portal}/app/agent-passkey#${Buffer.from(JSON.stringify(fragment)).toString('base64url')}`,
|
|
79
|
+
answer,
|
|
80
|
+
close() {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
o.signal.removeEventListener('abort', onAbort);
|
|
83
|
+
server.close();
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A question of the agent in an open view (WATCH.md § 6), and the prompt for
|
|
3
|
+
* its answer.
|
|
4
|
+
*
|
|
5
|
+
* Only the loop that reads the connection calls `connected`, `frame` and
|
|
6
|
+
* `stop`. The prompt runs beside it, because the connection must be read while
|
|
7
|
+
* a person types. Nothing else may write to the terminal while `asking`.
|
|
8
|
+
* What is typed is in memory only, and only until it is sent.
|
|
9
|
+
*/
|
|
10
|
+
import { ChannelEnd } from './relay.js';
|
|
11
|
+
import { clock, word } from './steps.js';
|
|
12
|
+
const ID = /^[0-9a-f]{32}$/;
|
|
13
|
+
const MAX_ANSWER = 4000;
|
|
14
|
+
/** What is typed before the keys were still for this long was meant for something else. */
|
|
15
|
+
const FRESH_MS = 1000;
|
|
16
|
+
const isText = (v) => typeof v === 'string' && v !== '';
|
|
17
|
+
/** The question in an `ask` frame. Null for a wrong shape. */
|
|
18
|
+
export function readAsk(f) {
|
|
19
|
+
const choices = f.choices;
|
|
20
|
+
if (!isText(f.id) || !ID.test(f.id) || !isText(f.text) || !Number.isSafeInteger(f.ends_at))
|
|
21
|
+
return null;
|
|
22
|
+
if (choices !== undefined && !(Array.isArray(choices) && choices.length >= 1 && choices.length <= 8 && choices.every(isText)))
|
|
23
|
+
return null;
|
|
24
|
+
return { id: f.id, reason: word(f.reason), text: f.text, choices, endsAt: f.ends_at };
|
|
25
|
+
}
|
|
26
|
+
/** The open question an `open` frame names: undefined when there is none, null for a wrong shape. */
|
|
27
|
+
export function questionOf(f) {
|
|
28
|
+
if (f.question === undefined)
|
|
29
|
+
return undefined;
|
|
30
|
+
return isText(f.question) && ID.test(f.question) ? f.question : null;
|
|
31
|
+
}
|
|
32
|
+
/** The `answer` frame for what was typed, or what is wrong with it. */
|
|
33
|
+
export function readAnswer(q, typed) {
|
|
34
|
+
const text = typed.trim();
|
|
35
|
+
if (q.choices) {
|
|
36
|
+
const n = /^[0-9]{1,2}$/.test(text) ? Number(text) : 0;
|
|
37
|
+
if (n < 1 || n > q.choices.length)
|
|
38
|
+
return `Type the number of a choice: ${range(q.choices.length)}.`;
|
|
39
|
+
return { t: 'answer', id: q.id, choice: n - 1 };
|
|
40
|
+
}
|
|
41
|
+
const length = [...text].length;
|
|
42
|
+
if (!length)
|
|
43
|
+
return 'Type an answer. It cannot be empty.';
|
|
44
|
+
if (length > MAX_ANSWER)
|
|
45
|
+
return `That is too long: ${length} characters. An answer has at most ${MAX_ANSWER}.`;
|
|
46
|
+
return { t: 'answer', id: q.id, text };
|
|
47
|
+
}
|
|
48
|
+
const range = (n) => (n === 1 ? '1' : `1 to ${n}`);
|
|
49
|
+
const OVER = {
|
|
50
|
+
no_answer: 'Nobody answered in time. The question is over.',
|
|
51
|
+
ended: 'The task ended before there was an answer. The question is over.',
|
|
52
|
+
};
|
|
53
|
+
function overText(f) {
|
|
54
|
+
if (f.state === 'answered')
|
|
55
|
+
return f.you === true ? 'Your answer was taken.' : 'Somebody else answered. The question is over.';
|
|
56
|
+
return OVER[word(f.state)] ?? `The question is over (${word(f.state)}).`;
|
|
57
|
+
}
|
|
58
|
+
/** What became of an answer when the view ends, or ''. */
|
|
59
|
+
function last(q) {
|
|
60
|
+
if (q.state === 'unsent')
|
|
61
|
+
return 'Your answer was not sent.';
|
|
62
|
+
return q.state === 'sent' ? 'It is not known if your answer was taken.' : '';
|
|
63
|
+
}
|
|
64
|
+
export class Questions {
|
|
65
|
+
d;
|
|
66
|
+
printer;
|
|
67
|
+
now = null;
|
|
68
|
+
channel = null;
|
|
69
|
+
may = false;
|
|
70
|
+
constructor(d, printer) {
|
|
71
|
+
this.d = d;
|
|
72
|
+
this.printer = printer;
|
|
73
|
+
}
|
|
74
|
+
get asking() {
|
|
75
|
+
return this.now?.state === 'asking';
|
|
76
|
+
}
|
|
77
|
+
/** Steps wait while a person answers, and until it is clear what came of the answer. */
|
|
78
|
+
get hold() {
|
|
79
|
+
return this.now !== null && this.now.state !== 'shown';
|
|
80
|
+
}
|
|
81
|
+
/** After each `open`. `question` is the one that is open now. */
|
|
82
|
+
async connected(channel, may, question) {
|
|
83
|
+
this.channel = channel;
|
|
84
|
+
this.may = may;
|
|
85
|
+
const q = this.now;
|
|
86
|
+
if (!q)
|
|
87
|
+
return;
|
|
88
|
+
if (q.ask.id !== question) {
|
|
89
|
+
await this.gone();
|
|
90
|
+
}
|
|
91
|
+
else if (q.state === 'unsent') {
|
|
92
|
+
this.send(q);
|
|
93
|
+
}
|
|
94
|
+
else if (q.state === 'sent') {
|
|
95
|
+
// Never sent twice by itself: the person may want another answer by now.
|
|
96
|
+
await this.d.say('The connection broke before your answer was taken, and the question is still open. Answer again.');
|
|
97
|
+
this.prompt(q);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** One inner frame. Other kinds than the three of a question are skipped. */
|
|
101
|
+
async frame(f) {
|
|
102
|
+
if (!['ask', 'ask_over', 'answer_refused'].includes(f.t))
|
|
103
|
+
return;
|
|
104
|
+
if (!isText(f.id) || !ID.test(f.id))
|
|
105
|
+
throw new ChannelEnd('bad_message');
|
|
106
|
+
const q = this.now;
|
|
107
|
+
if (f.t === 'ask') {
|
|
108
|
+
const ask = readAsk(f);
|
|
109
|
+
if (!ask)
|
|
110
|
+
throw new ChannelEnd('bad_message');
|
|
111
|
+
// It comes again after a resume.
|
|
112
|
+
if (q?.ask.id === ask.id)
|
|
113
|
+
return;
|
|
114
|
+
if (q)
|
|
115
|
+
await this.gone();
|
|
116
|
+
await this.show(ask);
|
|
117
|
+
}
|
|
118
|
+
else if (q?.ask.id !== f.id) {
|
|
119
|
+
// Of a question that is over here.
|
|
120
|
+
}
|
|
121
|
+
else if (f.t === 'ask_over') {
|
|
122
|
+
await this.over(overText(f));
|
|
123
|
+
}
|
|
124
|
+
else if (q.state !== 'sent') {
|
|
125
|
+
// A refusal of an answer this view did not send.
|
|
126
|
+
}
|
|
127
|
+
else if (f.code === 'over') {
|
|
128
|
+
await this.over('Your answer came too late: the question is over.');
|
|
129
|
+
}
|
|
130
|
+
else if (f.code === 'bad_answer') {
|
|
131
|
+
await this.d.say('The Agent Connector did not take that answer: it does not fit the question. Answer again.');
|
|
132
|
+
this.prompt(q);
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
q.state = 'shown';
|
|
136
|
+
await this.d.say(f.code === 'not_allowed' ? `Your answer was not taken. ${this.d.mayNot}` : `Your answer was not taken (${word(f.code)}).`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** The view is over. */
|
|
140
|
+
async stop() {
|
|
141
|
+
const q = this.now;
|
|
142
|
+
if (!q)
|
|
143
|
+
return;
|
|
144
|
+
await this.stopPrompt(q);
|
|
145
|
+
this.now = null;
|
|
146
|
+
if (last(q))
|
|
147
|
+
await this.d.say(last(q));
|
|
148
|
+
}
|
|
149
|
+
/** Ctrl-C: takes the prompt away and waits for nothing. Returns what there is to say about an answer, or ''. */
|
|
150
|
+
abort() {
|
|
151
|
+
this.now?.prompt?.stop.abort();
|
|
152
|
+
return this.now ? last(this.now) : '';
|
|
153
|
+
}
|
|
154
|
+
async show(ask) {
|
|
155
|
+
const q = { ask, state: 'shown' };
|
|
156
|
+
this.now = q;
|
|
157
|
+
await this.d.write(this.printer.question(ask.reason, ask.text, ask.choices ?? []));
|
|
158
|
+
await this.d.say(`The agent wrote this text, not Stav, and it may repeat what others wrote. It waits until ${clock(ask.endsAt)}.`);
|
|
159
|
+
if (!this.may) {
|
|
160
|
+
await this.d.say(this.d.mayNot);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (!ask.choices)
|
|
164
|
+
await this.d.say('Your answer goes to the agent and its model. Never type a password.');
|
|
165
|
+
this.prompt(q);
|
|
166
|
+
}
|
|
167
|
+
async over(text) {
|
|
168
|
+
if (this.now)
|
|
169
|
+
await this.stopPrompt(this.now);
|
|
170
|
+
this.now = null;
|
|
171
|
+
await this.d.say(text);
|
|
172
|
+
}
|
|
173
|
+
/** The end of the question was not heard. */
|
|
174
|
+
gone() {
|
|
175
|
+
return this.over(this.now?.state === 'sent'
|
|
176
|
+
? 'The question is over. It is not known if your answer was the one that was taken.'
|
|
177
|
+
: 'The question is over: it was answered, or it ended, without you.');
|
|
178
|
+
}
|
|
179
|
+
async stopPrompt(q) {
|
|
180
|
+
q.prompt?.stop.abort();
|
|
181
|
+
await q.prompt?.done;
|
|
182
|
+
}
|
|
183
|
+
prompt(q) {
|
|
184
|
+
q.state = 'asking';
|
|
185
|
+
const stop = new AbortController();
|
|
186
|
+
const done = this.run(q, stop.signal);
|
|
187
|
+
// Also when nobody waits for it.
|
|
188
|
+
done.catch(() => undefined);
|
|
189
|
+
q.prompt = { stop, done };
|
|
190
|
+
}
|
|
191
|
+
async run(q, signal) {
|
|
192
|
+
const line = q.ask.choices ? `Your answer (${range(q.ask.choices.length)}): ` : 'Your answer: ';
|
|
193
|
+
for (let freshMs = FRESH_MS;; freshMs = undefined) {
|
|
194
|
+
let typed;
|
|
195
|
+
try {
|
|
196
|
+
typed = await this.d.ask(line, { signal, freshMs, oneLine: true });
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
if (signal.aborted)
|
|
200
|
+
return;
|
|
201
|
+
// Ctrl-D. The steps go on with the next frame.
|
|
202
|
+
q.state = 'shown';
|
|
203
|
+
await this.d.say('You sent no answer. To answer, run stav agent watch again while the agent waits.');
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (signal.aborted)
|
|
207
|
+
return;
|
|
208
|
+
const answer = readAnswer(q.ask, typed);
|
|
209
|
+
if (typeof answer === 'string') {
|
|
210
|
+
await this.d.say(answer);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
q.answer = answer;
|
|
214
|
+
if (!this.send(q))
|
|
215
|
+
await this.d.say('The connection is away. Your answer is sent when it is back.');
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/** False when the connection has ended: then nothing left this computer. */
|
|
220
|
+
send(q) {
|
|
221
|
+
try {
|
|
222
|
+
this.channel.send(q.answer);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
q.state = 'unsent';
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
q.state = 'sent';
|
|
229
|
+
q.answer = undefined;
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The viewer's side of the relay (WATCH.md § 1) on Node's own WebSocket, and
|
|
3
|
+
* the encrypted channel on top of it (§ 2).
|
|
4
|
+
*
|
|
5
|
+
* The built-in client shows no ping and no HTTP status, and on Node 22 a
|
|
6
|
+
* refused connection gives "error" without a "close". So a connection ends on
|
|
7
|
+
* whichever comes first, once.
|
|
8
|
+
*/
|
|
9
|
+
import { StavError } from '../errors.js';
|
|
10
|
+
import { Handshake, NoiseError } from '../noise.js';
|
|
11
|
+
import { prologue } from './wire.js';
|
|
12
|
+
const MAX_CONTROL = 4096;
|
|
13
|
+
const MAX_INNER = 60_000;
|
|
14
|
+
/** The connector has at most 1 MiB unread for a viewer. More waiting here is not from it. */
|
|
15
|
+
const MAX_WAITING = 8 * 1024 * 1024;
|
|
16
|
+
/** The close codes that say something by themselves, for when the error frame is missing. */
|
|
17
|
+
const CLOSE_CODES = {
|
|
18
|
+
1011: 'internal', 4000: 'replaced', 4001: 'protocol', 4002: 'not_enabled', 4004: 'ticket_invalid', 4005: 'no_answer',
|
|
19
|
+
4006: 'too_many', 4007: 'ended', 4008: 'slow', 4009: 'timeout', 4010: 'agent_offline', 4011: 'closed',
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Why a connection ended: a relay code, or one of our own: `lost` (no reason
|
|
23
|
+
* given), `silent` (nothing heard in time) and `bad_message` (not from the
|
|
24
|
+
* paired connector).
|
|
25
|
+
*/
|
|
26
|
+
export class ChannelEnd extends Error {
|
|
27
|
+
code;
|
|
28
|
+
reason;
|
|
29
|
+
constructor(code, reason = '') {
|
|
30
|
+
super(code);
|
|
31
|
+
this.code = code;
|
|
32
|
+
this.reason = reason;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** `wss://<host>/watch`. Without TLS only on this computer. */
|
|
36
|
+
export function watchUrl(relayUrl) {
|
|
37
|
+
let u = null;
|
|
38
|
+
try {
|
|
39
|
+
u = new URL(relayUrl);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
// Said below.
|
|
43
|
+
}
|
|
44
|
+
const local = u !== null && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname);
|
|
45
|
+
if (!u || !(u.protocol === 'wss:' || (u.protocol === 'ws:' && local)) || u.pathname !== '/' || u.search || u.hash || u.username || u.password) {
|
|
46
|
+
throw new StavError('STAV_RELAY_URL must be wss:// and a host name, with nothing after it.', 'bad_relay_url');
|
|
47
|
+
}
|
|
48
|
+
return `${u.origin}/watch`;
|
|
49
|
+
}
|
|
50
|
+
const asObject = (text) => {
|
|
51
|
+
try {
|
|
52
|
+
const o = JSON.parse(text);
|
|
53
|
+
return o && typeof o === 'object' && !Array.isArray(o) ? o : null;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
export class RelayConnection {
|
|
60
|
+
ws;
|
|
61
|
+
waiting = [];
|
|
62
|
+
waitingBytes = 0;
|
|
63
|
+
wake = null;
|
|
64
|
+
end = null;
|
|
65
|
+
aborter = new AbortController();
|
|
66
|
+
/** When the last frame came, in milliseconds. */
|
|
67
|
+
heardAt = Date.now();
|
|
68
|
+
constructor(url) {
|
|
69
|
+
this.ws = new WebSocket(url);
|
|
70
|
+
this.ws.binaryType = 'arraybuffer';
|
|
71
|
+
this.ws.addEventListener('message', (ev) => this.onMessage(ev.data));
|
|
72
|
+
this.ws.addEventListener('error', () => this.finish(new ChannelEnd('lost')));
|
|
73
|
+
this.ws.addEventListener('close', (ev) => this.finish(new ChannelEnd(CLOSE_CODES[ev.code] ?? 'lost')));
|
|
74
|
+
}
|
|
75
|
+
onMessage(data) {
|
|
76
|
+
if (this.end)
|
|
77
|
+
return;
|
|
78
|
+
this.heardAt = Date.now();
|
|
79
|
+
const item = typeof data === 'string' ? data : Buffer.from(data);
|
|
80
|
+
if (typeof item === 'string') {
|
|
81
|
+
const o = item.length <= MAX_CONTROL ? asObject(item) : null;
|
|
82
|
+
if (o?.type === 'error') {
|
|
83
|
+
this.finish(new ChannelEnd(String(o.code), typeof o.reason === 'string' ? o.reason : ''));
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
this.waitingBytes += item.length;
|
|
88
|
+
if (this.waitingBytes > MAX_WAITING) {
|
|
89
|
+
this.finish(new ChannelEnd('bad_message'));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
this.waiting.push(item);
|
|
93
|
+
this.wake?.();
|
|
94
|
+
}
|
|
95
|
+
finish(end) {
|
|
96
|
+
if (this.end)
|
|
97
|
+
return;
|
|
98
|
+
this.end = end;
|
|
99
|
+
this.aborter.abort(end);
|
|
100
|
+
this.wake?.();
|
|
101
|
+
try {
|
|
102
|
+
this.ws.close();
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// Never opened.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Aborted when the connection ends, with the ChannelEnd as the reason. */
|
|
109
|
+
get ended() {
|
|
110
|
+
return this.aborter.signal;
|
|
111
|
+
}
|
|
112
|
+
close() {
|
|
113
|
+
this.finish(new ChannelEnd('lost'));
|
|
114
|
+
}
|
|
115
|
+
send(data) {
|
|
116
|
+
if (this.end)
|
|
117
|
+
throw this.end;
|
|
118
|
+
this.ws.send(data);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* The next frame. What came before the end is still given. `silent` after
|
|
122
|
+
* `ms` in which nothing at all came.
|
|
123
|
+
*/
|
|
124
|
+
async next(ms) {
|
|
125
|
+
const started = Date.now();
|
|
126
|
+
for (;;) {
|
|
127
|
+
const item = this.waiting.shift();
|
|
128
|
+
if (item !== undefined) {
|
|
129
|
+
this.waitingBytes -= item.length;
|
|
130
|
+
return item;
|
|
131
|
+
}
|
|
132
|
+
if (this.end)
|
|
133
|
+
throw this.end;
|
|
134
|
+
const left = Math.max(started, this.heardAt) + ms - Date.now();
|
|
135
|
+
if (left <= 0) {
|
|
136
|
+
this.finish(new ChannelEnd('silent'));
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
await new Promise((resolve) => {
|
|
140
|
+
const timer = setTimeout(resolve, left);
|
|
141
|
+
this.wake = () => {
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
resolve();
|
|
144
|
+
};
|
|
145
|
+
});
|
|
146
|
+
this.wake = null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** One view or one pairing: a finished handshake, and then inner frames both ways. */
|
|
151
|
+
export class Channel {
|
|
152
|
+
connection;
|
|
153
|
+
keys;
|
|
154
|
+
hash;
|
|
155
|
+
connectorKey;
|
|
156
|
+
constructor(connection, keys,
|
|
157
|
+
/** The handshake hash: what the passkey is bound to. */
|
|
158
|
+
hash, connectorKey) {
|
|
159
|
+
this.connection = connection;
|
|
160
|
+
this.keys = keys;
|
|
161
|
+
this.hash = hash;
|
|
162
|
+
this.connectorKey = connectorKey;
|
|
163
|
+
}
|
|
164
|
+
static async open(o) {
|
|
165
|
+
const c = new RelayConnection(o.url);
|
|
166
|
+
const control = async (type) => {
|
|
167
|
+
const f = await c.next(o.timeoutMs);
|
|
168
|
+
if (typeof f !== 'string' || asObject(f)?.type !== type)
|
|
169
|
+
throw new ChannelEnd('bad_message');
|
|
170
|
+
};
|
|
171
|
+
try {
|
|
172
|
+
await control('challenge');
|
|
173
|
+
c.send(JSON.stringify({ type: 'viewer', ticket: o.ticket }));
|
|
174
|
+
await control('welcome');
|
|
175
|
+
const hs = new Handshake({
|
|
176
|
+
kind: o.kind, initiator: true, prologue: prologue(o.kind, o.names), static: o.own, remoteStatic: o.connectorKey, psk: o.psk,
|
|
177
|
+
});
|
|
178
|
+
c.send(hs.write());
|
|
179
|
+
hs.read(await Channel.binary(c, o.timeoutMs));
|
|
180
|
+
if (!hs.done)
|
|
181
|
+
c.send(hs.write());
|
|
182
|
+
return new Channel(c, hs.split(), hs.hash, hs.remoteStatic);
|
|
183
|
+
}
|
|
184
|
+
catch (e) {
|
|
185
|
+
c.close();
|
|
186
|
+
throw e instanceof NoiseError ? new ChannelEnd('bad_message') : e;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
static async binary(c, ms) {
|
|
190
|
+
const f = await c.next(ms);
|
|
191
|
+
if (typeof f === 'string')
|
|
192
|
+
throw new ChannelEnd('bad_message');
|
|
193
|
+
return f;
|
|
194
|
+
}
|
|
195
|
+
send(frame) {
|
|
196
|
+
this.connection.send(this.keys.send.encrypt(Buffer.from(JSON.stringify(frame))));
|
|
197
|
+
}
|
|
198
|
+
/** The next inner frame, and how many bytes it had. */
|
|
199
|
+
async next(ms) {
|
|
200
|
+
try {
|
|
201
|
+
const plain = this.keys.receive.decrypt(await Channel.binary(this.connection, ms));
|
|
202
|
+
const frame = plain.length <= MAX_INNER ? asObject(new TextDecoder('utf-8', { fatal: true }).decode(plain)) : null;
|
|
203
|
+
if (typeof frame?.t !== 'string')
|
|
204
|
+
throw new ChannelEnd('bad_message');
|
|
205
|
+
return { frame: frame, size: plain.length };
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
this.close();
|
|
209
|
+
throw e instanceof ChannelEnd ? e : new ChannelEnd('bad_message');
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/** The next frame of one of these kinds; every other one is skipped. */
|
|
213
|
+
async wait(ms, ...kinds) {
|
|
214
|
+
const until = Date.now() + ms;
|
|
215
|
+
for (;;) {
|
|
216
|
+
const { frame } = await this.next(Math.max(1, until - Date.now()));
|
|
217
|
+
if (kinds.includes(frame.t))
|
|
218
|
+
return frame;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
close() {
|
|
222
|
+
this.connection.close();
|
|
223
|
+
}
|
|
224
|
+
}
|