@ulm0/gonogo 0.0.0-stage → 0.1.1
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 +30 -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-B6MsSoeo.css +1 -0
- package/dist/client/assets/index-DRtiRh1Y.js +31 -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/cleanroom.js +214 -0
- package/dist/server/cli.js +630 -0
- package/dist/server/command.js +44 -0
- package/dist/server/constants.js +427 -0
- package/dist/server/docking.js +541 -0
- package/dist/server/downlink.js +191 -0
- package/dist/server/home.js +497 -0
- package/dist/server/hooks.js +166 -0
- package/dist/server/hub.js +2484 -0
- package/dist/server/launcher.js +542 -0
- package/dist/server/livery.js +210 -0
- package/dist/server/logsearch.js +112 -0
- package/dist/server/mcp.js +196 -0
- package/dist/server/migrate.js +119 -0
- package/dist/server/missionlog.js +209 -0
- package/dist/server/payload.js +168 -0
- package/dist/server/propellant.js +314 -0
- package/dist/server/providers.js +137 -0
- package/dist/server/relay.js +300 -0
- package/dist/server/relaykinds.js +182 -0
- package/dist/server/schedules.js +277 -0
- package/dist/server/tasks.js +272 -0
- package/dist/server/terminal.js +635 -0
- package/dist/server/uplinks.js +356 -0
- package/dist/server/web.js +1466 -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 +212 -0
- package/package.json +84 -3
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Uplink: webhooks that start work (docs/uplink-spec.md).
|
|
3
|
+
*
|
|
4
|
+
* A delivery is `Hub.sendFromUser` with the subject "Uplink: <name>" and the JSON of the body pretty-printed, so Max Q,
|
|
5
|
+
* Redline and held mail apply as to a message typed in the Brief box. The endpoint (POST /uplink/:id) is outside /api and
|
|
6
|
+
* outside the browser token: a delivery proves itself with the uplink's secret, by a signature of the raw body or by the
|
|
7
|
+
* secret itself as a bearer token, compared in constant time. The kind of an uplink says how it proves itself and how its
|
|
8
|
+
* body becomes a message; Relay adds kinds by adding entries to KINDS. The clock and the send are injected for tests.
|
|
9
|
+
*
|
|
10
|
+
* shortcut: the secret is stored in the file as text (a signature cannot be checked against a hash), so the file is 0600
|
|
11
|
+
* and nothing else; encrypt it if the home folder is ever shared.
|
|
12
|
+
* shortcut: the rate limit counts only deliveries that prove themselves, so a stranger who guesses an id (u1) cannot use up
|
|
13
|
+
* the limit of the real sender, but can make the server hash 256 KiB per request; put a rate limit on the reverse proxy.
|
|
14
|
+
* shortcut: `to` is an agent name, so after a rename the deliveries end "refused" (409) until the uplink is edited; follow
|
|
15
|
+
* renames (key by record id) if renames get common.
|
|
16
|
+
*/
|
|
17
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
18
|
+
import { readFile, rename, writeFile } from 'node:fs/promises';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { ACTIVITY_STATUSES, AGENT_NAME_PATTERN, BODY_MAX_CHARS, UPLINK_DELIVERIES_MAX, UPLINK_GIVEN_SECRET_KINDS, UPLINK_KINDS, UPLINK_NAME_MAX_CHARS, UPLINKS_MAX, uplinkSubject, } from '../shared/protocol.js';
|
|
21
|
+
import { FILE_MODE, UPLINK_BAD_MAX, UPLINK_BAD_WINDOW_MS, UPLINK_NOTE_MAX_CHARS, UPLINK_RATE_MAX, UPLINK_RATE_WINDOW_MS, UPLINKS_FILE } from './constants.js';
|
|
22
|
+
import { HubError } from './hub.js';
|
|
23
|
+
import { bearerToken, isRecord } from './hooks.js';
|
|
24
|
+
import { RELAY_KINDS } from './relaykinds.js';
|
|
25
|
+
import { UNSAFE_IN_NAME } from './schedules.js';
|
|
26
|
+
const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
|
|
27
|
+
const ID_RE = /^u[1-9]\d{0,5}$/;
|
|
28
|
+
/** Made here: 64 hex characters. Given by Slack or Linear: whatever they made, printable. */
|
|
29
|
+
const SECRET_RE = /^[\x21-\x7e]{16,256}$/;
|
|
30
|
+
const SIGNATURE_RE = /^sha256=([0-9a-f]{64})$/i;
|
|
31
|
+
const CREATE_FIELDS = ['name', 'to', 'kind', 'enabled', 'secret'];
|
|
32
|
+
const PATCH_FIELDS = ['name', 'to', 'enabled', 'secret'];
|
|
33
|
+
/** Room left for the line that says a body was cut. */
|
|
34
|
+
const CUT_RESERVE = 120;
|
|
35
|
+
const NO_INBOUND = { find: () => undefined, seen: () => false, telegramChat: () => null };
|
|
36
|
+
/** The answer to a request that was good and not for the agents. */
|
|
37
|
+
const IGNORED = { ok: true, answer: { ok: true, ignored: true } };
|
|
38
|
+
const digest = (text) => createHash('sha256').update(text, 'utf8').digest();
|
|
39
|
+
/** `X-Gonogo-Signature: sha256=<hex HMAC-SHA256 of the raw body, keyed with the secret text>` or `Authorization: Bearer <secret>`. */
|
|
40
|
+
function genericAuthentic(raw, headers, secret) {
|
|
41
|
+
const signature = headers['x-gonogo-signature'];
|
|
42
|
+
const given = typeof signature === 'string' ? SIGNATURE_RE.exec(signature.trim()) : null;
|
|
43
|
+
if (given !== null && timingSafeEqual(Buffer.from(given[1], 'hex'), createHmac('sha256', secret).update(raw).digest()))
|
|
44
|
+
return true;
|
|
45
|
+
const token = bearerToken(headers.authorization);
|
|
46
|
+
return token !== null && timingSafeEqual(digest(token), digest(secret));
|
|
47
|
+
}
|
|
48
|
+
/** Any JSON, pretty-printed; cut to the body limit with a line that says so. */
|
|
49
|
+
function genericRead(raw) {
|
|
50
|
+
let text;
|
|
51
|
+
try {
|
|
52
|
+
// stringify is inside the try: JSON nested a hundred thousand deep parses but overflows the stack when written back
|
|
53
|
+
text = JSON.stringify(JSON.parse(raw.toString('utf8')), null, 2);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
throw new HubError('bad_request', 'the body is not JSON, or is nested too deep');
|
|
57
|
+
}
|
|
58
|
+
if (text.length <= BODY_MAX_CHARS)
|
|
59
|
+
return { text, cut: false };
|
|
60
|
+
const keep = BODY_MAX_CHARS - CUT_RESERVE;
|
|
61
|
+
return { text: `${text.slice(0, keep)}\n[cut: the delivery has ${text.length} characters, the first ${keep} are shown]`, cut: true };
|
|
62
|
+
}
|
|
63
|
+
const KINDS = { generic: { authentic: genericAuthentic, read: genericRead }, ...RELAY_KINDS };
|
|
64
|
+
const bad = (message, field) => new HubError('bad_request', message, field);
|
|
65
|
+
const cut = (text) => text.slice(0, UPLINK_NOTE_MAX_CHARS);
|
|
66
|
+
/** The fields a request may carry, checked one by one. With `whole` the two that have no default must be there. */
|
|
67
|
+
function validate(input, whole) {
|
|
68
|
+
if (!isRecord(input))
|
|
69
|
+
throw new HubError('bad_request', 'request body must be a JSON object');
|
|
70
|
+
const allowed = whole ? CREATE_FIELDS : PATCH_FIELDS;
|
|
71
|
+
for (const key of Object.keys(input))
|
|
72
|
+
if (!allowed.includes(key))
|
|
73
|
+
throw bad(`unknown field "${key}"`, key);
|
|
74
|
+
if (whole)
|
|
75
|
+
for (const key of ['name', 'to'])
|
|
76
|
+
if (input[key] === undefined)
|
|
77
|
+
throw bad(`${key} is required`, key);
|
|
78
|
+
const out = {};
|
|
79
|
+
if (input.name !== undefined) {
|
|
80
|
+
const name = typeof input.name === 'string' ? input.name.trim() : '';
|
|
81
|
+
if (name === '' || name.length > UPLINK_NAME_MAX_CHARS || UNSAFE_IN_NAME.test(name)) {
|
|
82
|
+
throw bad(`name must be 1 to ${UPLINK_NAME_MAX_CHARS} characters on one line`, 'name');
|
|
83
|
+
}
|
|
84
|
+
out.name = name;
|
|
85
|
+
}
|
|
86
|
+
if (input.to !== undefined) {
|
|
87
|
+
if (typeof input.to !== 'string' || (input.to !== 'boss' && (input.to === 'user' || !NAME_RE.test(input.to)))) {
|
|
88
|
+
throw bad('to must be an agent name or "boss"', 'to');
|
|
89
|
+
}
|
|
90
|
+
out.to = input.to;
|
|
91
|
+
}
|
|
92
|
+
if (input.kind !== undefined) {
|
|
93
|
+
if (typeof input.kind !== 'string' || !UPLINK_KINDS.includes(input.kind))
|
|
94
|
+
throw bad(`kind must be one of: ${UPLINK_KINDS.join(', ')}`, 'kind');
|
|
95
|
+
out.kind = input.kind;
|
|
96
|
+
}
|
|
97
|
+
if (input.enabled !== undefined) {
|
|
98
|
+
if (typeof input.enabled !== 'boolean')
|
|
99
|
+
throw bad('enabled must be true or false', 'enabled');
|
|
100
|
+
out.enabled = input.enabled;
|
|
101
|
+
}
|
|
102
|
+
if (input.secret !== undefined) {
|
|
103
|
+
if (typeof input.secret !== 'string' || !SECRET_RE.test(input.secret))
|
|
104
|
+
throw bad('secret must be 16 to 256 characters without spaces', 'secret');
|
|
105
|
+
out.secret = input.secret;
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
const givesSecret = (kind) => UPLINK_GIVEN_SECRET_KINDS.includes(kind);
|
|
110
|
+
/** The secret of a request must be there for the kinds that take the service's own, and not be there for the others. */
|
|
111
|
+
function checkSecret(kind, secret, required) {
|
|
112
|
+
if (secret === undefined && required && givesSecret(kind))
|
|
113
|
+
throw bad(`secret is required: it is the signing secret ${kind === 'slack' ? 'of the Slack app' : 'of the Linear webhook'}`, 'secret');
|
|
114
|
+
if (secret !== undefined && !givesSecret(kind))
|
|
115
|
+
throw bad(`a ${kind} uplink makes its own secret: only ${UPLINK_GIVEN_SECRET_KINDS.join(' and ')} take one`, 'secret');
|
|
116
|
+
}
|
|
117
|
+
/** What a saved delivery has to look like; anything else in the array is dropped. */
|
|
118
|
+
const isDelivery = (x) => isRecord(x) && typeof x.at === 'number' && typeof x.note === 'string' && typeof x.status === 'string' && (x.status === 'refused' || x.status === 'answered' || ACTIVITY_STATUSES.includes(x.status));
|
|
119
|
+
const viewOf = (u) => ({ id: u.id, name: u.name, kind: u.kind, to: u.to, enabled: u.enabled, createdAt: u.createdAt, deliveries: [...u.deliveries] });
|
|
120
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
121
|
+
export function createUplinks(options) {
|
|
122
|
+
const { dir, now, log } = options;
|
|
123
|
+
const inbound = options.inbound ?? NO_INBOUND;
|
|
124
|
+
const path = join(dir, UPLINKS_FILE);
|
|
125
|
+
let uplinks = [];
|
|
126
|
+
let seq = 0;
|
|
127
|
+
let chain = Promise.resolve();
|
|
128
|
+
/** When each uplink took its deliveries of the last minute, for the rate limit. Memory only. */
|
|
129
|
+
const taken = new Map();
|
|
130
|
+
/** Uplinks whose limit was hit and noted; cleared by the next delivery that gets through. */
|
|
131
|
+
const limited = new Set();
|
|
132
|
+
/** When each uplink was refused for a bad signature, and when the inbox was last told. Memory only. */
|
|
133
|
+
const refused = new Map();
|
|
134
|
+
const later = (fn) => {
|
|
135
|
+
const run = chain.then(fn);
|
|
136
|
+
chain = run.catch((error) => log.error('uplink could not write', error));
|
|
137
|
+
return run.then(() => undefined);
|
|
138
|
+
};
|
|
139
|
+
const save = () => {
|
|
140
|
+
const json = JSON.stringify({ version: 1, uplinks }, null, 2);
|
|
141
|
+
return later(async () => {
|
|
142
|
+
const tmp = join(dir, `.${UPLINKS_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
143
|
+
await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
|
|
144
|
+
await rename(tmp, path);
|
|
145
|
+
});
|
|
146
|
+
};
|
|
147
|
+
const list = () => uplinks.map(viewOf);
|
|
148
|
+
/** Tells the browsers and saves; a failed save is logged by `later`, so a caller that does not wait may ignore it. */
|
|
149
|
+
const changed = () => {
|
|
150
|
+
options.emit(list());
|
|
151
|
+
return save();
|
|
152
|
+
};
|
|
153
|
+
const find = (id) => {
|
|
154
|
+
const u = ID_RE.test(id) ? uplinks.find((x) => x.id === id) : undefined;
|
|
155
|
+
if (!u)
|
|
156
|
+
throw new HubError('not_found', 'unknown uplink');
|
|
157
|
+
return u;
|
|
158
|
+
};
|
|
159
|
+
const record = (u, status, note) => {
|
|
160
|
+
u.deliveries = [{ at: now(), status, note: cut(note) }, ...u.deliveries].slice(0, UPLINK_DELIVERIES_MAX);
|
|
161
|
+
void changed().catch(() => undefined);
|
|
162
|
+
};
|
|
163
|
+
/** Counts a request that did not prove itself; the inbox hears of it once per window, and never the secret. */
|
|
164
|
+
const refuse = (u) => {
|
|
165
|
+
const t = now();
|
|
166
|
+
const entry = refused.get(u.id) ?? { at: [], told: Number.NEGATIVE_INFINITY };
|
|
167
|
+
// only the newest UPLINK_BAD_MAX + 1 are kept: a flood of bad requests must not grow this list
|
|
168
|
+
entry.at = [...entry.at.filter((at) => t - at < UPLINK_BAD_WINDOW_MS), t].slice(-(UPLINK_BAD_MAX + 1));
|
|
169
|
+
refused.set(u.id, entry);
|
|
170
|
+
if (entry.at.length <= UPLINK_BAD_MAX || t - entry.told < UPLINK_BAD_WINDOW_MS)
|
|
171
|
+
return;
|
|
172
|
+
entry.told = t;
|
|
173
|
+
options.notify?.('uplink', `${u.name}: more than ${UPLINK_BAD_MAX} requests with a bad signature in ${UPLINK_BAD_WINDOW_MS / 60_000} minutes`);
|
|
174
|
+
};
|
|
175
|
+
/** One delivery of the last minute for `u`, or false when the limit is used up. */
|
|
176
|
+
const takeSlot = (u) => {
|
|
177
|
+
const t = now();
|
|
178
|
+
const times = (taken.get(u.id) ?? []).filter((at) => t - at < UPLINK_RATE_WINDOW_MS);
|
|
179
|
+
taken.set(u.id, times);
|
|
180
|
+
if (times.length >= UPLINK_RATE_MAX)
|
|
181
|
+
return false;
|
|
182
|
+
times.push(t);
|
|
183
|
+
return true;
|
|
184
|
+
};
|
|
185
|
+
/** Sends a message that a kind made and records what became of it. `label` starts the note ("test: "). Throws what `deliver` documents. */
|
|
186
|
+
const receive = (u, message, label) => {
|
|
187
|
+
try {
|
|
188
|
+
// a reply goes to the agent that wrote the message it answers, not to the one the uplink is set to
|
|
189
|
+
const request = { to: message.to ?? u.to, subject: message.subject ?? uplinkSubject(u.name), body: message.text, inReplyTo: message.inReplyTo };
|
|
190
|
+
let sent;
|
|
191
|
+
try {
|
|
192
|
+
sent = options.send(request);
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
// that agent was removed or renamed since: the uplink's own recipient gets the reply, so that the service is not
|
|
196
|
+
// answered 409 and does not send the same update again and again (Telegram does)
|
|
197
|
+
if (message.to === undefined || !(error instanceof HubError && error.code === 'not_found'))
|
|
198
|
+
throw error;
|
|
199
|
+
sent = options.send({ ...request, to: u.to });
|
|
200
|
+
}
|
|
201
|
+
record(u, sent.status, `${label}${sent.id}${sent.note ? `: ${sent.note}` : ''}${message.cut ? ' (cut)' : ''}`);
|
|
202
|
+
return sent;
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
record(u, 'refused', `${label}not sent: ${messageOf(error)}`);
|
|
206
|
+
// not "not found": that answer is for an uplink that does not exist
|
|
207
|
+
throw new HubError('conflict', messageOf(error));
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
return {
|
|
211
|
+
async load() {
|
|
212
|
+
let saved = null;
|
|
213
|
+
try {
|
|
214
|
+
saved = JSON.parse(await readFile(path, 'utf8'));
|
|
215
|
+
if (!isRecord(saved) || saved.version !== 1 || !Array.isArray(saved.uplinks))
|
|
216
|
+
throw new Error('not a version 1 uplinks file');
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
saved = null;
|
|
220
|
+
if (error.code !== 'ENOENT') {
|
|
221
|
+
// kept aside, so that the next save cannot overwrite the secrets the Director has handed out
|
|
222
|
+
// a SyntaxError quotes the text around the fault, which can be part of a secret
|
|
223
|
+
log.error(`${UPLINKS_FILE} could not be read; uplinks start empty and the file is kept as ${UPLINKS_FILE}.bad`, error instanceof SyntaxError ? 'not valid JSON' : error);
|
|
224
|
+
await rename(path, `${path}.bad`).catch(() => undefined);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const records = isRecord(saved) && Array.isArray(saved.uplinks) ? saved.uplinks : [];
|
|
228
|
+
for (const raw of records) {
|
|
229
|
+
try {
|
|
230
|
+
if (!isRecord(raw) || typeof raw.id !== 'string' || !ID_RE.test(raw.id))
|
|
231
|
+
throw new Error('no valid id');
|
|
232
|
+
if (uplinks.some((x) => x.id === raw.id))
|
|
233
|
+
throw new Error(`the id ${raw.id} is used twice`);
|
|
234
|
+
if (typeof raw.secret !== 'string' || !SECRET_RE.test(raw.secret))
|
|
235
|
+
throw new Error(`${raw.id} has no valid secret`);
|
|
236
|
+
const own = validate({ name: raw.name, to: raw.to, kind: raw.kind, enabled: raw.enabled }, true);
|
|
237
|
+
uplinks.push({
|
|
238
|
+
id: raw.id,
|
|
239
|
+
name: own.name ?? '',
|
|
240
|
+
kind: own.kind ?? 'generic',
|
|
241
|
+
to: own.to ?? '',
|
|
242
|
+
secret: raw.secret,
|
|
243
|
+
enabled: own.enabled === true,
|
|
244
|
+
createdAt: typeof raw.createdAt === 'number' ? raw.createdAt : now(),
|
|
245
|
+
deliveries: (Array.isArray(raw.deliveries) ? raw.deliveries.filter(isDelivery) : []).map((d) => ({ at: d.at, status: d.status, note: cut(d.note) })).slice(0, UPLINK_DELIVERIES_MAX),
|
|
246
|
+
});
|
|
247
|
+
seq = Math.max(seq, Number(raw.id.slice(1)));
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
log.warn(`${UPLINKS_FILE}: an uplink was skipped: ${messageOf(error)}`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
list,
|
|
255
|
+
async create(input) {
|
|
256
|
+
const request = validate(input, true);
|
|
257
|
+
const kind = request.kind ?? 'generic';
|
|
258
|
+
checkSecret(kind, request.secret, true);
|
|
259
|
+
if (uplinks.length >= UPLINKS_MAX)
|
|
260
|
+
throw new HubError('conflict', `at most ${UPLINKS_MAX} uplinks`);
|
|
261
|
+
seq += 1;
|
|
262
|
+
const u = {
|
|
263
|
+
id: `u${seq}`,
|
|
264
|
+
name: request.name,
|
|
265
|
+
kind,
|
|
266
|
+
to: request.to,
|
|
267
|
+
secret: request.secret ?? randomBytes(32).toString('hex'),
|
|
268
|
+
enabled: request.enabled ?? true,
|
|
269
|
+
createdAt: now(),
|
|
270
|
+
deliveries: [],
|
|
271
|
+
};
|
|
272
|
+
uplinks.push(u);
|
|
273
|
+
await changed();
|
|
274
|
+
return { ...viewOf(u), secret: u.secret };
|
|
275
|
+
},
|
|
276
|
+
async update(id, input) {
|
|
277
|
+
const u = find(id);
|
|
278
|
+
const patch = validate(input, false);
|
|
279
|
+
checkSecret(u.kind, patch.secret, false);
|
|
280
|
+
Object.assign(u, patch);
|
|
281
|
+
await changed();
|
|
282
|
+
return viewOf(u);
|
|
283
|
+
},
|
|
284
|
+
async remove(id) {
|
|
285
|
+
const u = find(id);
|
|
286
|
+
uplinks = uplinks.filter((x) => x !== u);
|
|
287
|
+
taken.delete(id);
|
|
288
|
+
limited.delete(id);
|
|
289
|
+
refused.delete(id);
|
|
290
|
+
await changed();
|
|
291
|
+
},
|
|
292
|
+
async rotate(id) {
|
|
293
|
+
const u = find(id);
|
|
294
|
+
if (givesSecret(u.kind))
|
|
295
|
+
throw new HubError('conflict', `the secret of a ${u.kind} uplink is the one the service made: set it by editing the uplink`);
|
|
296
|
+
u.secret = randomBytes(32).toString('hex');
|
|
297
|
+
await changed();
|
|
298
|
+
return { ...viewOf(u), secret: u.secret };
|
|
299
|
+
},
|
|
300
|
+
async test(id) {
|
|
301
|
+
const u = find(id);
|
|
302
|
+
try {
|
|
303
|
+
// the sample is JSON whatever the kind: it proves the way to the agent, not the signature of a service
|
|
304
|
+
receive(u, genericRead(Buffer.from(JSON.stringify({ test: true, uplink: u.name, at: new Date(now()).toISOString() }))), 'test: ');
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
// the refusal is in the delivery that `receive` recorded
|
|
308
|
+
}
|
|
309
|
+
await chain;
|
|
310
|
+
return viewOf(u);
|
|
311
|
+
},
|
|
312
|
+
deliver(id, raw, headers) {
|
|
313
|
+
const u = ID_RE.test(id) ? uplinks.find((x) => x.id === id) : undefined;
|
|
314
|
+
if (!u || !u.enabled)
|
|
315
|
+
throw new HubError('not_found', 'not found');
|
|
316
|
+
if (!KINDS[u.kind].authentic(raw, headers, u.secret, now())) {
|
|
317
|
+
// not recorded: anyone who guesses an id could fill the list of deliveries
|
|
318
|
+
log.debug(`uplink ${u.id}: a request did not prove itself`);
|
|
319
|
+
refuse(u);
|
|
320
|
+
throw new HubError('unauthorized', 'unauthorized');
|
|
321
|
+
}
|
|
322
|
+
let made;
|
|
323
|
+
try {
|
|
324
|
+
made = KINDS[u.kind].read(raw, headers, inbound);
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
record(u, 'refused', messageOf(error));
|
|
328
|
+
throw error;
|
|
329
|
+
}
|
|
330
|
+
// before the rate limit: what the agents never hear of (chatter in a channel) must not use up the deliveries of a minute
|
|
331
|
+
if (made === null)
|
|
332
|
+
return IGNORED;
|
|
333
|
+
if ('answer' in made) {
|
|
334
|
+
record(u, 'answered', made.note);
|
|
335
|
+
return { ok: true, answer: made.answer };
|
|
336
|
+
}
|
|
337
|
+
if (!takeSlot(u)) {
|
|
338
|
+
// noted once per flood, as the hub does for an agent's limit: a note per refusal would push out the real deliveries
|
|
339
|
+
if (!limited.has(u.id)) {
|
|
340
|
+
limited.add(u.id);
|
|
341
|
+
record(u, 'refused', `rate limit: more than ${UPLINK_RATE_MAX} deliveries in a minute`);
|
|
342
|
+
}
|
|
343
|
+
throw new HubError('rate_limited', `at most ${UPLINK_RATE_MAX} deliveries a minute`);
|
|
344
|
+
}
|
|
345
|
+
limited.delete(u.id);
|
|
346
|
+
// after the limit: an event that was refused for it is not marked handled, so Slack's retry can still get through
|
|
347
|
+
if (made.once !== undefined && inbound.seen(made.once))
|
|
348
|
+
return IGNORED;
|
|
349
|
+
const sent = receive(u, made, '');
|
|
350
|
+
return { ok: sent.ok, id: sent.id, status: sent.status };
|
|
351
|
+
},
|
|
352
|
+
close() {
|
|
353
|
+
return chain.then(() => undefined);
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
}
|