@ulm0/gonogo 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +24 -2
- package/bin/gonogo.js +18 -0
- package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
- package/dist/client/apple-touch-icon.png +0 -0
- package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
- package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
- package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
- package/dist/client/assets/index-BqCn1SM7.js +50 -0
- package/dist/client/assets/index-KZtFVMJG.css +1 -0
- package/dist/client/favicon.ico +0 -0
- package/dist/client/favicon.svg +1 -0
- package/dist/client/index.html +19 -0
- package/dist/server/audited.js +133 -0
- package/dist/server/blackbox.js +261 -0
- package/dist/server/board.js +123 -0
- package/dist/server/cleanroom.js +214 -0
- package/dist/server/clearance.js +158 -0
- package/dist/server/cli.js +763 -0
- package/dist/server/command.js +44 -0
- package/dist/server/constants.js +465 -0
- package/dist/server/docking.js +541 -0
- package/dist/server/downlink.js +191 -0
- package/dist/server/hangar.js +311 -0
- package/dist/server/home.js +520 -0
- package/dist/server/hooks.js +166 -0
- package/dist/server/hub.js +2642 -0
- package/dist/server/launcher.js +547 -0
- package/dist/server/livery.js +210 -0
- package/dist/server/logchart.js +58 -0
- package/dist/server/logsearch.js +112 -0
- package/dist/server/massbudget.js +169 -0
- package/dist/server/mcp.js +228 -0
- package/dist/server/migrate.js +122 -0
- package/dist/server/missionlog.js +211 -0
- package/dist/server/payload.js +168 -0
- package/dist/server/propellant.js +314 -0
- package/dist/server/providers.js +199 -0
- package/dist/server/recorder.js +176 -0
- package/dist/server/relay.js +300 -0
- package/dist/server/relaykinds.js +182 -0
- package/dist/server/relief.js +226 -0
- package/dist/server/rollout.js +172 -0
- package/dist/server/schedules.js +277 -0
- package/dist/server/tasks.js +272 -0
- package/dist/server/telemetry.js +110 -0
- package/dist/server/terminal.js +635 -0
- package/dist/server/uplinks.js +356 -0
- package/dist/server/web.js +1607 -0
- package/dist/shared/cron.js +149 -0
- package/dist/shared/fuel.js +18 -0
- package/dist/shared/livery.js +348 -0
- package/dist/shared/positions.js +132 -0
- package/dist/shared/protocol.js +245 -0
- package/package.json +84 -3
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Docking: two gonogo installations connect so that their agents can message each other and hand off work
|
|
3
|
+
* (docs/docking-spec.md).
|
|
4
|
+
*
|
|
5
|
+
* Pairing: the Director of A makes a docking code (A's public address and a one-time token, valid 15 minutes) and the
|
|
6
|
+
* Director of B pastes it. B proves it holds the token with an HMAC and does not send it; A answers with a proof of its own,
|
|
7
|
+
* and both derive the same 32-byte secret from the token and two nonces, so the secret never crosses the wire. Every later
|
|
8
|
+
* call goes to /dock/* (outside /api and the browser token) signed with HMAC-SHA256 over the method, the path, a timestamp,
|
|
9
|
+
* a nonce and the body; a timestamp more than 5 minutes from now or a nonce seen before is refused, and a dock may make 60
|
|
10
|
+
* calls a minute. What crosses: the roster (pulled every 30 s), a message (it becomes a message from "name@station" there),
|
|
11
|
+
* a task of the Flight Plan, and the undock. The clock, the fetch and the timer are injected for tests.
|
|
12
|
+
*
|
|
13
|
+
* shortcut: the secret is stored in docking.json as text, a 0600 file; encrypt it if the home folder is ever shared.
|
|
14
|
+
* shortcut: the answer of another station is read whole before it is looked at; it is a station the Director chose to
|
|
15
|
+
* dock with. Cap it if a station you do not trust is ever docked.
|
|
16
|
+
* shortcut: the address of a station is an origin (no path), so a station behind a path prefix cannot be docked.
|
|
17
|
+
* shortcut: a docking code and the nonces seen live in memory; a restart forgets them (a code stops working, a replay of a
|
|
18
|
+
* call from the last 5 minutes before the restart would be accepted once).
|
|
19
|
+
*/
|
|
20
|
+
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
21
|
+
import { readFile, rename, writeFile } from 'node:fs/promises';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
import { AGENT_NAME_PATTERN, AGENT_STATES, API_ERROR_CODES, DOCKS_MAX, MAX_AGENTS, STATION_NAME_PATTERN, TASK_DETAIL_MAX_CHARS, } from '../shared/protocol.js';
|
|
24
|
+
import { DOCK_BODY_MAX_BYTES, DOCK_CODE_TTL_MS, DOCK_CODES_MAX, DOCK_PULL_MS, DOCK_RATE_MAX, DOCK_RATE_WINDOW_MS, DOCK_SKEW_MS, DOCK_TIMEOUT_MS, DOCK_UNDOCK_TIMEOUT_MS, DOCKING_FILE, FILE_MODE, ROSTER_ROLE_CHARS, STATION_FILE, } from './constants.js';
|
|
25
|
+
import { isRecord } from './hooks.js';
|
|
26
|
+
import { HubError } from './hub.js';
|
|
27
|
+
const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
|
|
28
|
+
const STATION_RE = new RegExp(STATION_NAME_PATTERN);
|
|
29
|
+
const HEX32_RE = /^[0-9a-f]{32}$/;
|
|
30
|
+
const HEX64_RE = /^[0-9a-f]{64}$/;
|
|
31
|
+
const NONCE_RE = /^[0-9a-f]{16,64}$/;
|
|
32
|
+
const TASK_ID_RE = /^t[1-9]\d{0,5}$/;
|
|
33
|
+
const CODE_PREFIX = 'gonogo-dock:';
|
|
34
|
+
/** The routes under /dock and the one method each takes. */
|
|
35
|
+
export const DOCK_ROUTES = { pair: 'POST', roster: 'GET', message: 'POST', task: 'POST', undock: 'POST' };
|
|
36
|
+
/** The name of this station: GONOGO_STATION, else the first label of the host name, cut to the shape of a name. */
|
|
37
|
+
export function stationName(raw, host) {
|
|
38
|
+
const cut = (text) => text
|
|
39
|
+
.toLowerCase()
|
|
40
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
41
|
+
.replace(/^-+/, '')
|
|
42
|
+
.slice(0, 31)
|
|
43
|
+
.replace(/-+$/, '');
|
|
44
|
+
return cut(raw ?? '') || cut(host.split('.')[0] ?? '') || 'station';
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The signature of one call: HMAC-SHA256 with the secret (hex) over the sender's station id, method, path, timestamp, nonce
|
|
48
|
+
* and body. The id is signed because both sides hold the same secret: without it a call of ours could be sent back to us as
|
|
49
|
+
* one from the other side. Exported for the tests and the docs.
|
|
50
|
+
*/
|
|
51
|
+
export function signCall(secret, station, method, path, timestamp, nonce, body) {
|
|
52
|
+
return createHmac('sha256', Buffer.from(secret, 'hex')).update(`${station}\n${method}\n${path}\n${timestamp}\n${nonce}\n`).update(body).digest('hex');
|
|
53
|
+
}
|
|
54
|
+
/** The proofs of the pairing, keyed with the token of the code. The first part says which proof it is, so one cannot stand for another. */
|
|
55
|
+
const mac = (token, ...parts) => createHmac('sha256', token).update(parts.join('\n')).digest('hex');
|
|
56
|
+
const sameText = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
57
|
+
const random = (bytes) => randomBytes(bytes).toString('hex');
|
|
58
|
+
const bad = (message, field) => new HubError('bad_request', message, field);
|
|
59
|
+
/** Text another station sent, as it lands in a note or an error here. */
|
|
60
|
+
const clip = (text) => text.slice(0, 300);
|
|
61
|
+
/** A web address with no path: the origin of a station, as the other side will reach it. */
|
|
62
|
+
function publicUrl(value, field) {
|
|
63
|
+
const fail = bad(`${field} must be a web address with no path, such as https://gonogo.example.com`, field);
|
|
64
|
+
let url;
|
|
65
|
+
try {
|
|
66
|
+
url = new URL(typeof value === 'string' ? value.trim() : '');
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw fail;
|
|
70
|
+
}
|
|
71
|
+
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '' || url.pathname !== '/')
|
|
72
|
+
throw fail;
|
|
73
|
+
return url.origin;
|
|
74
|
+
}
|
|
75
|
+
function readObject(body) {
|
|
76
|
+
let value = null;
|
|
77
|
+
try {
|
|
78
|
+
value = JSON.parse(body.toString('utf8'));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// answered below, like a body that parses to something else than an object
|
|
82
|
+
}
|
|
83
|
+
if (!isRecord(value))
|
|
84
|
+
throw bad('request body must be a JSON object');
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
const one = (value) => (typeof value === 'string' ? value : '');
|
|
88
|
+
/** Why a call to another station did not answer, in a few words. */
|
|
89
|
+
function causeOf(error) {
|
|
90
|
+
if (error instanceof Error && error.name === 'TimeoutError')
|
|
91
|
+
return `no answer within ${DOCK_TIMEOUT_MS / 1000} s`;
|
|
92
|
+
const code = error instanceof Error ? error.cause?.code : undefined;
|
|
93
|
+
return typeof code === 'string' ? code : error instanceof Error ? error.message : String(error);
|
|
94
|
+
}
|
|
95
|
+
/** What another station refused with, as an error of ours. Its 401, 403 and 404 are not ours: the browser reads a 401 as a lost key. */
|
|
96
|
+
function remoteError(label, status, data) {
|
|
97
|
+
const info = isRecord(data) ? data : {};
|
|
98
|
+
const message = typeof info.error === 'string' ? clip(info.error) : `answered ${status}`;
|
|
99
|
+
const code = API_ERROR_CODES.includes(String(info.code)) ? info.code : 'unavailable';
|
|
100
|
+
const field = typeof info.field === 'string' ? info.field : undefined;
|
|
101
|
+
if (code === 'unauthorized' || code === 'forbidden' || code === 'not_found')
|
|
102
|
+
return new HubError('conflict', `${label} refused: ${message}`);
|
|
103
|
+
return new HubError(code, `${label}: ${message}`, code === 'bad_request' ? field : undefined);
|
|
104
|
+
}
|
|
105
|
+
function readAgents(value) {
|
|
106
|
+
if (!Array.isArray(value))
|
|
107
|
+
return [];
|
|
108
|
+
const agents = [];
|
|
109
|
+
for (const raw of value) {
|
|
110
|
+
if (agents.length >= MAX_AGENTS)
|
|
111
|
+
break;
|
|
112
|
+
if (!isRecord(raw) || typeof raw.name !== 'string' || !NAME_RE.test(raw.name))
|
|
113
|
+
continue;
|
|
114
|
+
const state = AGENT_STATES.includes(raw.state) ? raw.state : 'stopped';
|
|
115
|
+
agents.push({ name: raw.name, role: typeof raw.role === 'string' ? raw.role.slice(0, ROSTER_ROLE_CHARS) : '', state, boss: raw.boss === true });
|
|
116
|
+
}
|
|
117
|
+
return agents;
|
|
118
|
+
}
|
|
119
|
+
export function createDocking(options) {
|
|
120
|
+
const { dir, now, log } = options;
|
|
121
|
+
const path = join(dir, DOCKING_FILE);
|
|
122
|
+
let id = '';
|
|
123
|
+
let docks = [];
|
|
124
|
+
const live = new Map();
|
|
125
|
+
/** Docking codes that were made and not used: token to expiry. */
|
|
126
|
+
const pending = new Map();
|
|
127
|
+
const pairCalls = [];
|
|
128
|
+
/** Tasks on their way to another station, so that two clicks do not copy one twice. */
|
|
129
|
+
const handing = new Set();
|
|
130
|
+
let lastSig = '';
|
|
131
|
+
let stopTimer = null;
|
|
132
|
+
let chain = Promise.resolve();
|
|
133
|
+
const later = (fn) => {
|
|
134
|
+
const run = chain.then(fn);
|
|
135
|
+
chain = run.catch((error) => log.error('docking could not write', error));
|
|
136
|
+
return run.then(() => undefined);
|
|
137
|
+
};
|
|
138
|
+
const writeAtomic = (file, text) => later(async () => {
|
|
139
|
+
const tmp = join(dir, `.${file}.${process.pid}.${random(4)}.tmp`);
|
|
140
|
+
await writeFile(tmp, text, { mode: FILE_MODE, flag: 'wx' });
|
|
141
|
+
await rename(tmp, join(dir, file));
|
|
142
|
+
});
|
|
143
|
+
const save = () => writeAtomic(DOCKING_FILE, JSON.stringify({ version: 1, docks }, null, 2));
|
|
144
|
+
const liveOf = (dock) => {
|
|
145
|
+
let state = live.get(dock.id);
|
|
146
|
+
if (!state) {
|
|
147
|
+
state = { status: 'new', seenAt: null, error: null, agents: [], pulling: false, nonces: new Map(), calls: [] };
|
|
148
|
+
live.set(dock.id, state);
|
|
149
|
+
}
|
|
150
|
+
return state;
|
|
151
|
+
};
|
|
152
|
+
const dockView = (dock) => {
|
|
153
|
+
const state = liveOf(dock);
|
|
154
|
+
return { id: dock.id, name: dock.name, url: dock.url, since: dock.since, status: state.status, seenAt: state.seenAt, error: state.error, agents: state.agents.map((a) => ({ ...a })) };
|
|
155
|
+
};
|
|
156
|
+
const view = () => ({ station: options.name, docks: docks.map(dockView) });
|
|
157
|
+
/** Tells the browsers, unless nothing they show has changed since the last time. */
|
|
158
|
+
const publish = () => {
|
|
159
|
+
const next = view();
|
|
160
|
+
const sig = JSON.stringify(next);
|
|
161
|
+
if (sig === lastSig)
|
|
162
|
+
return;
|
|
163
|
+
lastSig = sig;
|
|
164
|
+
options.emit(next);
|
|
165
|
+
};
|
|
166
|
+
const find = (dockId) => {
|
|
167
|
+
const dock = docks.find((d) => d.id === dockId);
|
|
168
|
+
if (!dock)
|
|
169
|
+
throw new HubError('not_found', 'unknown dock');
|
|
170
|
+
return dock;
|
|
171
|
+
};
|
|
172
|
+
const byName = (name) => docks.find((d) => d.name === name);
|
|
173
|
+
/** A name another station may take: not ours and not the name of another dock. */
|
|
174
|
+
const nameFree = (name, except) => name !== options.name && !docks.some((d) => d.name === name && d.id !== except);
|
|
175
|
+
const dropOldCodes = () => {
|
|
176
|
+
for (const [token, expiresAt] of pending)
|
|
177
|
+
if (expiresAt <= now())
|
|
178
|
+
pending.delete(token);
|
|
179
|
+
};
|
|
180
|
+
/** The accepted calls of a minute against DOCK_RATE_MAX. */
|
|
181
|
+
const takeCall = (calls) => {
|
|
182
|
+
const at = now();
|
|
183
|
+
while (calls.length > 0 && at - calls[0] >= DOCK_RATE_WINDOW_MS)
|
|
184
|
+
calls.shift();
|
|
185
|
+
if (calls.length >= DOCK_RATE_MAX)
|
|
186
|
+
throw new HubError('rate_limited', 'too many calls this minute');
|
|
187
|
+
calls.push(at);
|
|
188
|
+
};
|
|
189
|
+
/* ---------------------------------------------------------------- the calls we make */
|
|
190
|
+
async function transport(label, url, method, headers, body, timeoutMs) {
|
|
191
|
+
let text;
|
|
192
|
+
let status;
|
|
193
|
+
try {
|
|
194
|
+
const response = await options.fetch(url, { method, headers, body, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
|
|
195
|
+
status = response.status;
|
|
196
|
+
text = await response.text();
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
throw new HubError('unavailable', `could not reach ${label}: ${causeOf(error)}`);
|
|
200
|
+
}
|
|
201
|
+
let data = null;
|
|
202
|
+
try {
|
|
203
|
+
data = JSON.parse(text);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
// not JSON: an error below
|
|
207
|
+
}
|
|
208
|
+
if (status < 200 || status > 299)
|
|
209
|
+
throw remoteError(label, status, data);
|
|
210
|
+
if (!isRecord(data))
|
|
211
|
+
throw new HubError('unavailable', `${label} sent an answer that is not JSON`);
|
|
212
|
+
return data;
|
|
213
|
+
}
|
|
214
|
+
/** A signed call to a docked station. */
|
|
215
|
+
function call(dock, method, route, payload, timeoutMs = DOCK_TIMEOUT_MS) {
|
|
216
|
+
const urlPath = `/dock/${route}`;
|
|
217
|
+
const body = method === 'POST' ? JSON.stringify(payload ?? {}) : '';
|
|
218
|
+
const timestamp = String(now());
|
|
219
|
+
const nonce = random(16);
|
|
220
|
+
const headers = {
|
|
221
|
+
'x-gonogo-station': id,
|
|
222
|
+
'x-gonogo-timestamp': timestamp,
|
|
223
|
+
'x-gonogo-nonce': nonce,
|
|
224
|
+
'x-gonogo-signature': signCall(dock.secret, id, method, urlPath, timestamp, nonce, body),
|
|
225
|
+
};
|
|
226
|
+
if (method === 'POST')
|
|
227
|
+
headers['content-type'] = 'application/json';
|
|
228
|
+
return transport(dock.name, dock.url + urlPath, method, headers, method === 'POST' ? body : undefined, timeoutMs);
|
|
229
|
+
}
|
|
230
|
+
/** Asks one station for its roster. Its failure is what the dock shows, not an error. */
|
|
231
|
+
async function pullOne(dock) {
|
|
232
|
+
const state = liveOf(dock);
|
|
233
|
+
if (state.pulling)
|
|
234
|
+
return;
|
|
235
|
+
state.pulling = true;
|
|
236
|
+
try {
|
|
237
|
+
const answer = await call(dock, 'GET', 'roster');
|
|
238
|
+
const station = isRecord(answer.station) ? answer.station : {};
|
|
239
|
+
if (station.id !== dock.id)
|
|
240
|
+
throw new HubError('conflict', 'the station at this address is not the one that was docked');
|
|
241
|
+
// it may rename itself; the name is the part after the @, so two docks never share one
|
|
242
|
+
if (typeof station.name === 'string' && station.name !== dock.name && STATION_RE.test(station.name) && nameFree(station.name, dock.id)) {
|
|
243
|
+
dock.name = station.name;
|
|
244
|
+
// a write that fails is logged by the chain; nobody waits for it here
|
|
245
|
+
save().catch(() => undefined);
|
|
246
|
+
}
|
|
247
|
+
state.agents = readAgents(answer.agents);
|
|
248
|
+
state.status = 'ok';
|
|
249
|
+
state.seenAt = now();
|
|
250
|
+
state.error = null;
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
state.status = 'down';
|
|
254
|
+
state.error = error instanceof Error ? error.message : String(error);
|
|
255
|
+
log.debug(`pull of ${dock.name} failed`, error);
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
state.pulling = false;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
async function pull() {
|
|
262
|
+
await Promise.all(docks.map((d) => pullOne(d)));
|
|
263
|
+
publish();
|
|
264
|
+
}
|
|
265
|
+
/* ---------------------------------------------------------------- the calls we get */
|
|
266
|
+
/** Who sent this call, or a 401. The signature comes first, so that what it covers (the time, the nonce) can be told to the sender. */
|
|
267
|
+
function authenticate(method, url, headers, body) {
|
|
268
|
+
const refused = new HubError('unauthorized', 'the call is not signed by a docked station');
|
|
269
|
+
const station = one(headers['x-gonogo-station']);
|
|
270
|
+
const timestamp = one(headers['x-gonogo-timestamp']);
|
|
271
|
+
const nonce = one(headers['x-gonogo-nonce']);
|
|
272
|
+
const signature = one(headers['x-gonogo-signature']);
|
|
273
|
+
const dock = HEX32_RE.test(station) ? docks.find((d) => d.id === station) : undefined;
|
|
274
|
+
if (!dock || !/^\d{10,16}$/.test(timestamp) || !NONCE_RE.test(nonce) || !HEX64_RE.test(signature))
|
|
275
|
+
throw refused;
|
|
276
|
+
if (!sameText(signature, signCall(dock.secret, station, method, url, timestamp, nonce, body)))
|
|
277
|
+
throw refused;
|
|
278
|
+
const at = now();
|
|
279
|
+
if (Math.abs(at - Number(timestamp)) > DOCK_SKEW_MS)
|
|
280
|
+
throw new HubError('unauthorized', 'the timestamp is more than 5 minutes from this station\'s clock');
|
|
281
|
+
const state = liveOf(dock);
|
|
282
|
+
for (const [seen, until] of state.nonces)
|
|
283
|
+
if (until <= at)
|
|
284
|
+
state.nonces.delete(seen);
|
|
285
|
+
if (state.nonces.has(nonce))
|
|
286
|
+
throw new HubError('unauthorized', 'this call was made before');
|
|
287
|
+
takeCall(state.calls);
|
|
288
|
+
// a call with this timestamp is refused for its age from the moment it is DOCK_SKEW_MS old, so the nonce is of no use after that
|
|
289
|
+
state.nonces.set(nonce, Number(timestamp) + DOCK_SKEW_MS);
|
|
290
|
+
return dock;
|
|
291
|
+
}
|
|
292
|
+
/** The other side proves it holds a code; the answer proves we made it. Both then have the secret. */
|
|
293
|
+
async function acceptPair(body) {
|
|
294
|
+
takeCall(pairCalls);
|
|
295
|
+
const { id: theirId, name, url, nonce, proof } = body;
|
|
296
|
+
if (typeof theirId !== 'string' || !HEX32_RE.test(theirId))
|
|
297
|
+
throw bad('id must be a station id', 'id');
|
|
298
|
+
if (typeof name !== 'string' || !STATION_RE.test(name))
|
|
299
|
+
throw bad('name must be a station name', 'name');
|
|
300
|
+
if (typeof nonce !== 'string' || !NONCE_RE.test(nonce))
|
|
301
|
+
throw bad('nonce must be hex text', 'nonce');
|
|
302
|
+
if (typeof proof !== 'string' || !HEX64_RE.test(proof))
|
|
303
|
+
throw bad('proof must be hex text', 'proof');
|
|
304
|
+
const theirUrl = publicUrl(url, 'url');
|
|
305
|
+
dropOldCodes();
|
|
306
|
+
let token = null;
|
|
307
|
+
for (const candidate of pending.keys())
|
|
308
|
+
if (sameText(proof, mac(candidate, 'pair', nonce, theirId, name, theirUrl)))
|
|
309
|
+
token = candidate;
|
|
310
|
+
if (token === null)
|
|
311
|
+
throw new HubError('unauthorized', 'the code is wrong, used or expired');
|
|
312
|
+
if (theirId === id)
|
|
313
|
+
throw new HubError('conflict', 'a station cannot dock with itself');
|
|
314
|
+
if (docks.some((d) => d.id === theirId))
|
|
315
|
+
throw new HubError('conflict', `already docked with ${name}`);
|
|
316
|
+
if (!nameFree(name, theirId))
|
|
317
|
+
throw new HubError('conflict', `a station called ${name} is this one or is docked already: one of them has to change its name (GONOGO_STATION)`);
|
|
318
|
+
if (docks.length >= DOCKS_MAX)
|
|
319
|
+
throw new HubError('conflict', `at most ${DOCKS_MAX} stations can be docked`);
|
|
320
|
+
pending.delete(token);
|
|
321
|
+
const mine = random(16);
|
|
322
|
+
const dock = { id: theirId, name, url: theirUrl, secret: mac(token, 'secret', mine, nonce, id, theirId), since: now() };
|
|
323
|
+
docks.push(dock);
|
|
324
|
+
await save();
|
|
325
|
+
publish();
|
|
326
|
+
// no pull yet: the other side has not saved the dock until it reads this answer. Its first pull, right after, makes us pull.
|
|
327
|
+
return { id, name: options.name, nonce: mine, ack: mac(token, 'ack', nonce, mine, id, options.name) };
|
|
328
|
+
}
|
|
329
|
+
function acceptMessage(dock, body) {
|
|
330
|
+
// the hub checks every field of a message from a station, as it does for one from an agent
|
|
331
|
+
return options.deliver(dock.name, body);
|
|
332
|
+
}
|
|
333
|
+
async function acceptTask(dock, body) {
|
|
334
|
+
const theirs = typeof body.id === 'string' && TASK_ID_RE.test(body.id) ? ` (its task ${body.id})` : '';
|
|
335
|
+
const detail = typeof body.detail === 'string' ? body.detail : '';
|
|
336
|
+
const request = {
|
|
337
|
+
title: body.title,
|
|
338
|
+
detail: `Handed off from ${dock.name}${theirs}.${detail === '' ? '' : `\n\n${detail}`}`.slice(0, TASK_DETAIL_MAX_CHARS),
|
|
339
|
+
};
|
|
340
|
+
if (body.assignee !== undefined && body.assignee !== null)
|
|
341
|
+
request.assignee = body.assignee;
|
|
342
|
+
const task = await options.tasks.create({ kind: 'dock', station: dock.name }, request);
|
|
343
|
+
return { ok: true, id: task.id };
|
|
344
|
+
}
|
|
345
|
+
/* ---------------------------------------------------------------- the public API */
|
|
346
|
+
return {
|
|
347
|
+
async load() {
|
|
348
|
+
let saved = null;
|
|
349
|
+
try {
|
|
350
|
+
saved = JSON.parse(await readFile(join(dir, STATION_FILE), 'utf8'));
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
// none yet, or not readable: a new id below
|
|
354
|
+
}
|
|
355
|
+
id = isRecord(saved) && typeof saved.id === 'string' && HEX32_RE.test(saved.id) ? saved.id : '';
|
|
356
|
+
if (id === '') {
|
|
357
|
+
id = random(16);
|
|
358
|
+
await writeAtomic(STATION_FILE, JSON.stringify({ version: 1, id }, null, 2));
|
|
359
|
+
}
|
|
360
|
+
saved = null;
|
|
361
|
+
try {
|
|
362
|
+
saved = JSON.parse(await readFile(path, 'utf8'));
|
|
363
|
+
if (!isRecord(saved) || saved.version !== 1 || !Array.isArray(saved.docks))
|
|
364
|
+
throw new Error('not a version 1 docking file');
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
saved = null;
|
|
368
|
+
if (error.code !== 'ENOENT') {
|
|
369
|
+
// kept aside, so that the next save cannot overwrite the secrets that were agreed
|
|
370
|
+
log.error(`${DOCKING_FILE} could not be read; no station is docked and the file is kept as ${DOCKING_FILE}.bad`, error instanceof SyntaxError ? 'not valid JSON' : error);
|
|
371
|
+
await rename(path, `${path}.bad`).catch(() => undefined);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
for (const raw of isRecord(saved) && Array.isArray(saved.docks) ? saved.docks : []) {
|
|
375
|
+
if (!isRecord(raw) || typeof raw.id !== 'string' || !HEX32_RE.test(raw.id) || typeof raw.name !== 'string' || !STATION_RE.test(raw.name))
|
|
376
|
+
continue;
|
|
377
|
+
if (typeof raw.secret !== 'string' || !HEX64_RE.test(raw.secret) || typeof raw.url !== 'string' || docks.some((d) => d.id === raw.id || d.name === raw.name))
|
|
378
|
+
continue;
|
|
379
|
+
docks.push({ id: raw.id, name: raw.name, url: raw.url, secret: raw.secret, since: typeof raw.since === 'number' ? raw.since : now() });
|
|
380
|
+
}
|
|
381
|
+
lastSig = JSON.stringify(view());
|
|
382
|
+
},
|
|
383
|
+
start() {
|
|
384
|
+
const every = options.every ?? ((fn, ms) => {
|
|
385
|
+
const timer = setInterval(fn, ms);
|
|
386
|
+
timer.unref();
|
|
387
|
+
return () => clearInterval(timer);
|
|
388
|
+
});
|
|
389
|
+
stopTimer = every(() => void pull(), DOCK_PULL_MS);
|
|
390
|
+
void pull();
|
|
391
|
+
},
|
|
392
|
+
view,
|
|
393
|
+
stations: () => docks.map((d) => d.name),
|
|
394
|
+
rosters: () => docks.filter((d) => liveOf(d).status === 'ok' && liveOf(d).agents.length > 0).map((d) => ({ station: d.name, agents: liveOf(d).agents.map((a) => ({ ...a })) })),
|
|
395
|
+
async send(station, message) {
|
|
396
|
+
const dock = byName(station);
|
|
397
|
+
if (!dock)
|
|
398
|
+
return { ok: false, note: `${station} is not docked` };
|
|
399
|
+
try {
|
|
400
|
+
const answer = await call(dock, 'POST', 'message', message);
|
|
401
|
+
const status = typeof answer.status === 'string' ? clip(answer.status) : 'unknown';
|
|
402
|
+
const note = typeof answer.note === 'string' && answer.note !== '' ? `, ${clip(answer.note)}` : '';
|
|
403
|
+
// the other hub's own words: its message is "undelivered" when it went to its Director
|
|
404
|
+
if (answer.ok !== true)
|
|
405
|
+
return { ok: false, note: `${station} did not deliver it: ${status}${note}` };
|
|
406
|
+
return { ok: true, note: `accepted by ${station}: ${status}${note}` };
|
|
407
|
+
}
|
|
408
|
+
catch (error) {
|
|
409
|
+
return { ok: false, note: error instanceof Error ? error.message : String(error) };
|
|
410
|
+
}
|
|
411
|
+
},
|
|
412
|
+
createCode(input) {
|
|
413
|
+
if (!isRecord(input))
|
|
414
|
+
throw bad('request body must be a JSON object');
|
|
415
|
+
const url = publicUrl(input.url, 'url');
|
|
416
|
+
dropOldCodes();
|
|
417
|
+
while (pending.size >= DOCK_CODES_MAX)
|
|
418
|
+
pending.delete(pending.keys().next().value);
|
|
419
|
+
const token = random(32);
|
|
420
|
+
const expiresAt = now() + DOCK_CODE_TTL_MS;
|
|
421
|
+
pending.set(token, expiresAt);
|
|
422
|
+
return { code: CODE_PREFIX + Buffer.from(JSON.stringify({ u: url, t: token })).toString('base64url'), expiresAt };
|
|
423
|
+
},
|
|
424
|
+
async pair(input) {
|
|
425
|
+
if (!isRecord(input))
|
|
426
|
+
throw bad('request body must be a JSON object');
|
|
427
|
+
const own = publicUrl(input.url, 'url');
|
|
428
|
+
let theirs;
|
|
429
|
+
try {
|
|
430
|
+
const text = typeof input.code === 'string' ? input.code.trim() : '';
|
|
431
|
+
if (!text.startsWith(CODE_PREFIX))
|
|
432
|
+
throw new Error('no prefix');
|
|
433
|
+
const parsed = JSON.parse(Buffer.from(text.slice(CODE_PREFIX.length), 'base64url').toString('utf8'));
|
|
434
|
+
if (!isRecord(parsed) || typeof parsed.t !== 'string' || !HEX64_RE.test(parsed.t))
|
|
435
|
+
throw new Error('no token');
|
|
436
|
+
theirs = { u: publicUrl(parsed.u, 'code'), t: parsed.t };
|
|
437
|
+
}
|
|
438
|
+
catch {
|
|
439
|
+
throw bad('code is not a docking code: copy the whole of it from the other station', 'code');
|
|
440
|
+
}
|
|
441
|
+
if (docks.length >= DOCKS_MAX)
|
|
442
|
+
throw new HubError('conflict', `at most ${DOCKS_MAX} stations can be docked`);
|
|
443
|
+
const nonce = random(16);
|
|
444
|
+
const answer = await transport(new URL(theirs.u).host, `${theirs.u}/dock/pair`, 'POST', { 'content-type': 'application/json' }, JSON.stringify({ id, name: options.name, url: own, nonce, proof: mac(theirs.t, 'pair', nonce, id, options.name, own) }), DOCK_TIMEOUT_MS);
|
|
445
|
+
const { id: theirId, name, nonce: mine, ack } = answer;
|
|
446
|
+
if (typeof theirId !== 'string' || !HEX32_RE.test(theirId) || typeof name !== 'string' || !STATION_RE.test(name) || typeof mine !== 'string' || !NONCE_RE.test(mine) || typeof ack !== 'string') {
|
|
447
|
+
throw bad('the station at that address did not answer as a gonogo station', 'code');
|
|
448
|
+
}
|
|
449
|
+
if (!sameText(ack, mac(theirs.t, 'ack', nonce, mine, theirId, name)))
|
|
450
|
+
throw bad('the station at that address did not prove it made this code: check the address and ask for a new code', 'code');
|
|
451
|
+
const dock = { id: theirId, name, url: theirs.u, secret: mac(theirs.t, 'secret', mine, nonce, theirId, id), since: now() };
|
|
452
|
+
const refusal = docks.some((d) => d.id === theirId)
|
|
453
|
+
? new HubError('conflict', `already docked with ${name}: undock it here first`)
|
|
454
|
+
: !nameFree(name, theirId)
|
|
455
|
+
? new HubError('conflict', `a station called ${name} is this one or is docked already: one of them has to change its name (GONOGO_STATION)`)
|
|
456
|
+
: null;
|
|
457
|
+
if (refusal) {
|
|
458
|
+
// the other side docked already: it is told to undock, so that it does not keep a dock that this side never made
|
|
459
|
+
await call(dock, 'POST', 'undock', {}, DOCK_UNDOCK_TIMEOUT_MS).catch((error) => log.debug(`${name} was not told to undo the pairing`, error));
|
|
460
|
+
throw refusal;
|
|
461
|
+
}
|
|
462
|
+
docks.push(dock);
|
|
463
|
+
await save();
|
|
464
|
+
publish();
|
|
465
|
+
void pullOne(dock).then(publish);
|
|
466
|
+
return dockView(dock);
|
|
467
|
+
},
|
|
468
|
+
async undock(dockId) {
|
|
469
|
+
const dock = find(dockId);
|
|
470
|
+
let told = true;
|
|
471
|
+
try {
|
|
472
|
+
await call(dock, 'POST', 'undock', {}, DOCK_UNDOCK_TIMEOUT_MS);
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
told = false;
|
|
476
|
+
log.debug(`${dock.name} was not told of the undock`, error);
|
|
477
|
+
}
|
|
478
|
+
docks = docks.filter((d) => d !== dock);
|
|
479
|
+
live.delete(dock.id);
|
|
480
|
+
await save();
|
|
481
|
+
publish();
|
|
482
|
+
return { told };
|
|
483
|
+
},
|
|
484
|
+
async handOff(dockId, input) {
|
|
485
|
+
const dock = find(dockId);
|
|
486
|
+
if (!isRecord(input))
|
|
487
|
+
throw bad('request body must be a JSON object');
|
|
488
|
+
for (const key of Object.keys(input))
|
|
489
|
+
if (key !== 'task' && key !== 'assignee')
|
|
490
|
+
throw bad(`unknown field "${key}"`, key);
|
|
491
|
+
const task = options.tasks.list().find((t) => t.id === input.task);
|
|
492
|
+
if (!task)
|
|
493
|
+
throw new HubError('not_found', 'unknown task', 'task');
|
|
494
|
+
if (task.status === 'done' || task.handedOff !== undefined || handing.has(task.id))
|
|
495
|
+
throw new HubError('conflict', 'only a task that is open here can be handed off', 'task');
|
|
496
|
+
const assignee = input.assignee ?? null;
|
|
497
|
+
if (assignee !== null && (typeof assignee !== 'string' || !NAME_RE.test(assignee)))
|
|
498
|
+
throw bad('assignee must be the name of an agent of that station, or null', 'assignee');
|
|
499
|
+
handing.add(task.id);
|
|
500
|
+
try {
|
|
501
|
+
await call(dock, 'POST', 'task', { id: task.id, title: task.title, detail: task.detail, assignee });
|
|
502
|
+
return await options.tasks.handOff(task.id, dock.name, assignee);
|
|
503
|
+
}
|
|
504
|
+
finally {
|
|
505
|
+
handing.delete(task.id);
|
|
506
|
+
}
|
|
507
|
+
},
|
|
508
|
+
async handle(route, method, url, headers, body) {
|
|
509
|
+
if (body.length > DOCK_BODY_MAX_BYTES)
|
|
510
|
+
throw new HubError('too_large', 'request body too large');
|
|
511
|
+
if (route === 'pair')
|
|
512
|
+
return acceptPair(readObject(body));
|
|
513
|
+
const dock = authenticate(method, url, headers, body);
|
|
514
|
+
// it calls in, so it answers calls too: this is the first pull of the side that made the code, and the next one of a dock that was down
|
|
515
|
+
if (route !== 'undock' && liveOf(dock).status !== 'ok')
|
|
516
|
+
void pullOne(dock).then(publish);
|
|
517
|
+
switch (route) {
|
|
518
|
+
case 'roster':
|
|
519
|
+
return { station: { id, name: options.name }, agents: options.roster() };
|
|
520
|
+
case 'message':
|
|
521
|
+
return acceptMessage(dock, readObject(body));
|
|
522
|
+
case 'task':
|
|
523
|
+
return acceptTask(dock, readObject(body));
|
|
524
|
+
default: {
|
|
525
|
+
// undock: gone from here too, and the answer is the last thing this dock gets
|
|
526
|
+
docks = docks.filter((d) => d !== dock);
|
|
527
|
+
live.delete(dock.id);
|
|
528
|
+
await save();
|
|
529
|
+
publish();
|
|
530
|
+
return { ok: true };
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
},
|
|
534
|
+
pull,
|
|
535
|
+
close() {
|
|
536
|
+
stopTimer?.();
|
|
537
|
+
stopTimer = null;
|
|
538
|
+
return chain.then(() => undefined);
|
|
539
|
+
},
|
|
540
|
+
};
|
|
541
|
+
}
|