sigelo-contact 0.1.7 → 0.1.8
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 +21 -19
- package/carrier.mjs +192 -36
- package/enrol.mjs +12 -8
- package/envelope.mjs +4 -4
- package/invite.mjs +4 -4
- package/kdf.mjs +6 -0
- package/package.json +4 -3
- package/prekeys.mjs +4 -4
- package/short.mjs +23 -0
- package/test-short.mjs +32 -1
- package/test-ws.mjs +237 -0
package/README.md
CHANGED
|
@@ -9,28 +9,30 @@ the other's sigelo chain offline; a key rotation keeps the contact. MIT; the rel
|
|
|
9
9
|
```sh
|
|
10
10
|
sigelo-agent invite --name bob # alice: K7F3-Q9ZP, once, 10 minutes
|
|
11
11
|
sigelo-agent accept <code> --name alice # bob: checks alice offline, pairs
|
|
12
|
-
sigelo-agent send bob "hello" # sent, or queued
|
|
12
|
+
sigelo-agent send bob "hello" # sent, or queued for bob
|
|
13
13
|
seq 3 | sigelo-agent send bob - --lines # one message a line, one login
|
|
14
14
|
sigelo-agent inbox # what came since last time
|
|
15
15
|
```
|
|
16
16
|
|
|
17
17
|
Also `contacts`, `forget <did>`, and all as MCP tools
|
|
18
18
|
([`integrations/mcp/contact.mjs`](../integrations/mcp/contact.mjs)).
|
|
19
|
-
Each verb logs in once (30 a minute per network), never beside
|
|
19
|
+
Each verb logs in once (30 a minute per network), never beside `watch` or `ui`
|
|
20
20
|
([one owner](../adapters/moadim/WATCH.md)).
|
|
21
|
-
The first login proves work (5–60 s on a phone). `SIGELO_RELAY` names the relay for new codes
|
|
22
|
-
|
|
21
|
+
The first login proves work (5–60 s on a phone). `SIGELO_RELAY` names the relay for new codes;
|
|
22
|
+
a Pro reader sets `SIGELO_RELAY_RETENTION_DAYS=90`. State sits
|
|
23
23
|
beside the identity file (0600); messages wait there in plaintext until `inbox` takes them.
|
|
24
24
|
`carrier.mjs`'s header is its API; with `onEvent`, nothing is kept.
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
**Sandboxes and firewalls.** Messaging dials only the relay, `relay.sigelo.ai` by default: 8883, else
|
|
27
|
+
443 (automatic; `SIGELO_RELAY_TRANSPORT=wss` skips the 5 s probe). `HTTPS_PROXY`, `NO_PROXY` apply.
|
|
28
|
+
Allow that hostname on 443; install needs the npm registry.
|
|
27
29
|
|
|
28
|
-
|
|
30
|
+
## Tests
|
|
29
31
|
|
|
30
32
|
```sh
|
|
31
33
|
node test-invite.mjs && node test-envelope.mjs
|
|
32
|
-
node test-carrier.mjs
|
|
33
|
-
sh ../demo/two-machines.sh
|
|
34
|
+
node test-carrier.mjs && node test-ws.mjs # with ../relay, on loopback
|
|
35
|
+
sh ../demo/two-machines.sh
|
|
34
36
|
```
|
|
35
37
|
|
|
36
38
|
## Contracts
|
|
@@ -46,31 +48,31 @@ Each regenerates byte for byte from seeds (`gen-*.mjs`); refusals name their che
|
|
|
46
48
|
|
|
47
49
|
## How it works
|
|
48
50
|
|
|
49
|
-
1. **Code**: the inviter's current DID digest, a one-time secret
|
|
50
|
-
|
|
51
|
+
1. **Code**: the inviter's current DID digest, a one-time secret (yielding both invite topics and
|
|
52
|
+
their key), expiry, relay, checksum.
|
|
51
53
|
2. **Handshake**: bob answers with his chain, a proof for this code and a one-time X-Wing key;
|
|
52
54
|
alice checks it and replies with her chain, prekeys and the encapsulation, all signed.
|
|
53
55
|
`K = HKDF(secret ‖ X-Wing secret)`; each keeps the other under its original DID.
|
|
54
|
-
3. **Mailboxes**: one topic per direction per ISO week, from `K`, held from retention
|
|
55
|
-
|
|
56
|
+
3. **Mailboxes**: one topic per direction per ISO week, from `K`, held from retention to a week
|
|
57
|
+
ahead.
|
|
56
58
|
4. **Envelope**: signed by the identity key, encrypted (XChaCha20-Poly1305) under a chain begun
|
|
57
|
-
on a single-use prekey
|
|
59
|
+
on a recipient's single-use prekey, padded to whole 256-byte blocks. Until the sender
|
|
58
60
|
reads a reply, each envelope repeats the encapsulation: a reader offline past retention loses
|
|
59
61
|
those messages, not the epoch. Prekeys travel under `K`, replaced weekly.
|
|
60
62
|
5. **Rotation**: the rotated agent sends each contact its chain under `K`, proven by its new key,
|
|
61
63
|
until the contact confirms it, so recovery beats a thief (SPEC §7.1). After a recovery both
|
|
62
64
|
mark the pairing `re_pair`: only that notice goes under `K` until a new code replaces it.
|
|
63
|
-
6. **Relay login**: a signed `{v:"sigelo-relay/0", typ:"relay-login", did, relay, nonce}`,
|
|
64
|
-
|
|
65
|
+
6. **Relay login**: a signed `{v:"sigelo-relay/0", typ:"relay-login", did, relay, nonce}`, which
|
|
66
|
+
no challenge signer produces.
|
|
65
67
|
|
|
66
|
-
Key agreement is hybrid post-quantum (X25519 + ML-KEM-768)
|
|
68
|
+
Key agreement is hybrid post-quantum (X25519 + ML-KEM-768).
|
|
67
69
|
|
|
68
70
|
## What it does not do
|
|
69
71
|
|
|
70
|
-
- Find anyone (codes travel out of band), hide who talks to whom
|
|
72
|
+
- Find anyone (codes travel out of band), hide who talks to whom, or deny.
|
|
71
73
|
- Heal inside an epoch after a key theft (no double ratchet): a stolen state file reads what
|
|
72
74
|
contacts write until the next weekly prekey replacement.
|
|
73
75
|
- Confirm delivery (the relay acknowledges, not the contact): a relay withholding an epoch's key
|
|
74
76
|
agreement loses what follows until fresh prekeys restart it.
|
|
75
|
-
- Check where a stranger's relay resolves
|
|
76
|
-
- Push, groups, direct delivery,
|
|
77
|
+
- Check where a stranger's relay resolves (only its name).
|
|
78
|
+
- Push, groups, direct delivery, unsend.
|
package/carrier.mjs
CHANGED
|
@@ -3,10 +3,12 @@
|
|
|
3
3
|
// invite answers and replies and sigelo-msg/0 envelopes between contacts through a relay. The relay
|
|
4
4
|
// sees random topics and ciphertext; everything here that decides who someone is runs offline.
|
|
5
5
|
//
|
|
6
|
-
// const c = new Carrier({ identity, store, state, relay, endpoints, retentionDays, clock, onEvent, keep })
|
|
6
|
+
// const c = new Carrier({ identity, store, state, relay, endpoints, retentionDays, clock, onEvent, keep, transport })
|
|
7
7
|
// await c.invite({ name, ttl, short }) → { code, did, relay, exp, short?, short_exp? } the answer topic is claimed first;
|
|
8
8
|
// short: the long code is also parked at the relay under a short one
|
|
9
9
|
// await c.unpark(short) → the long code parked under a short one, taken from the relay (one use)
|
|
10
|
+
// await c.redeemGift(code) → { exp, months }: a gift code (PRO-K7F3-Q9ZP) redeemed at this agent's relay;
|
|
11
|
+
// this identity is the operator whose pool is Pro until exp (relay/gifts.mjs)
|
|
10
12
|
// await c.accept(code, { name, wait }) → { status: 'connected' | 'waiting' | 'pending', … } a long code or a short one
|
|
11
13
|
// (refused after a short code was fetched: .long, keepLong)
|
|
12
14
|
// await c.cancelInvite(code) → { cancelled, name }: an unanswered invite of this agent's withdrawn
|
|
@@ -37,8 +39,9 @@
|
|
|
37
39
|
// c.clockOffset(), await c.checkClock() → { relay, offset, checked } | null: the relay's clock less this one's, seconds
|
|
38
40
|
// await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
|
|
39
41
|
//
|
|
40
|
-
// identity() → {
|
|
41
|
-
//
|
|
42
|
+
// identity() → { sign, bundle }: the agent's signer for its current key (sign(body) → the SPEC §3
|
|
43
|
+
// signature; sigelo-agent-keys.ts) and its SPEC §8 bundle, read again at every operation, so a
|
|
44
|
+
// rotation made by another process is seen at once. { secret, bundle }, the seed itself, still works. store: the contact store
|
|
42
45
|
// (store.mjs); state: this file's own JSON (sessions, outbox, inbox), both 0600 and written under one
|
|
43
46
|
// lock file, `<state>.lock`. pathsFor(identityFile) names both beside the identity file. onEvent(e):
|
|
44
47
|
// each event as it happens, messages included, and `pow` / `pow_done` around a proof-of-work search
|
|
@@ -51,6 +54,14 @@
|
|
|
51
54
|
// lock; the started one reconnects with backoff). Beside one, use inbox and send with local: the
|
|
52
55
|
// state file only (sigelo-agent's one-owner rule, adapters/moadim/WATCH.md).
|
|
53
56
|
//
|
|
57
|
+
// Transport (transport, or SIGELO_RELAY_TRANSPORT): "auto" (the default), 8883 for PROBE_MS, then
|
|
58
|
+
// 443 for the rest of the process, so a network that lets only HTTPS out needs no setting; "mqtts",
|
|
59
|
+
// MQTT over TLS on 8883 only; "wss", MQTT over WebSocket on 443 only (wss://host/mqtt, or
|
|
60
|
+
// relay.json's endpoints.mqtt_ws on the same host), which skips the probe. Both are TLS. HTTPS_PROXY (or https_proxy), an http:// proxy, carries the HTTPS calls
|
|
61
|
+
// and the WebSocket dial by HTTP CONNECT, unless NO_PROXY (or no_proxy) names the host (proxyFor);
|
|
62
|
+
// MQTT on 8883 never goes through it. Certificates are checked as without a proxy, so
|
|
63
|
+
// NODE_EXTRA_CA_CERTS works the same. The event { type: "transport" } says when auto fell back.
|
|
64
|
+
//
|
|
54
65
|
// What this adds to the wire, beside the envelope (envelope.mjs) and the invite (invite.mjs); the
|
|
55
66
|
// bytes are pinned in fixtures/carrier-v0.json (gen-carrier.mjs --check):
|
|
56
67
|
// - Frames for the invite answer (kind 1), the invite reply (kind 2), the contact notice (kind 4)
|
|
@@ -173,6 +184,9 @@
|
|
|
173
184
|
// round, so topics are asked in the order they matter (#want). A refused topic is asked again
|
|
174
185
|
// at the next hourly round (ASK_AGAIN).
|
|
175
186
|
import { createHash } from 'node:crypto';
|
|
187
|
+
import { request as httpRequest } from 'node:http';
|
|
188
|
+
import { Agent as HttpsAgent, request as httpsRequest } from 'node:https';
|
|
189
|
+
import { connect as tlsConnect } from 'node:tls';
|
|
176
190
|
import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
177
191
|
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
178
192
|
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
|
@@ -181,13 +195,13 @@ import { hmac } from '@noble/hashes/hmac.js';
|
|
|
181
195
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
182
196
|
import { concatBytes, hexToBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
183
197
|
import { connect } from 'mqtt';
|
|
184
|
-
import { canonicalize, commitmentOf, did as didOf, parseBytes,
|
|
198
|
+
import { canonicalize, commitmentOf, did as didOf, parseBytes, verify, verifySig } from 'sigelo';
|
|
185
199
|
import { KIND, acceptPrekeys, expire, header, open, pad, prekeysMissing, restartEpoch, send, session, unpad } from './envelope.mjs';
|
|
186
200
|
import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, inviteKeys, keyOf, makeInvite, parseInvite } from './invite.mjs';
|
|
187
|
-
import { MsgError, checkNow, fail, hex, isoWeek, pairId, topic } from './kdf.mjs';
|
|
201
|
+
import { MsgError, checkNow, fail, hex, isoWeek, pairId, signAs, topic } from './kdf.mjs';
|
|
188
202
|
import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
|
|
189
203
|
import { Contacts, OPERATOR_CTX, TIERS } from './store.mjs';
|
|
190
|
-
import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, makeShort, normaliseShort } from './short.mjs';
|
|
204
|
+
import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, giftHash, makeShort, normaliseShort } from './short.mjs';
|
|
191
205
|
import { FILE_LABEL, MAX_FILE, assemble, checkChunk, checkManifest, chunkHead, isManifest, safeName, splitFile } from './file.mjs';
|
|
192
206
|
|
|
193
207
|
export const V = 'sigelo-carrier/0';
|
|
@@ -236,6 +250,13 @@ const FILES_OPEN = 8;
|
|
|
236
250
|
const RATE = { perSecond: 10, burst: 100 };
|
|
237
251
|
// Milliseconds. QUIET: no delivery for this long after connecting = the relay's queue is drained.
|
|
238
252
|
const QUIET = 400, DRAIN = 4000, ACK_MS = 15000, CONNECT_MS = 15000, HTTP_MS = 15000, HTTP_MAX = 65536;
|
|
253
|
+
// transport "auto": MQTT over TLS gets this long to answer the CONNECT before the dial goes to MQTT
|
|
254
|
+
// over WebSocket on 443. A network that lets only HTTPS out drops 8883 rather than refusing it.
|
|
255
|
+
export const PROBE_MS = 5000;
|
|
256
|
+
export const TRANSPORTS = ['mqtts', 'wss', 'auto'];
|
|
257
|
+
// The WebSocket endpoint, as relay.json names it (relay/server.mjs WS_PATH) and as a relay with
|
|
258
|
+
// none is reached: on its HTTPS host.
|
|
259
|
+
export const WS_PATH = '/mqtt';
|
|
239
260
|
// MQTT.js buffers a packet whole before handing it over, up to MQTT's 256 MB (its own size check
|
|
240
261
|
// applies only to protocol version 5), and a code can name any host: a packet longer than the
|
|
241
262
|
// largest a relay forwards (relay/server.mjs MAX_FRAME: a 1 MB message and its header) cuts the
|
|
@@ -311,6 +332,8 @@ const theirPrekeys = (c, d, pair, now) => {
|
|
|
311
332
|
const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
|
|
312
333
|
// The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
|
|
313
334
|
const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_CHECKS]);
|
|
335
|
+
// The refusals of POST /gift this client names (relay/gifts.mjs, allowance.mjs, operator.mjs, and the login's).
|
|
336
|
+
const GIFT_CHECKS = new Set(['gift', 'gift_member', 'gift_term', 'pow', ...LOGIN_CHECKS]);
|
|
314
337
|
|
|
315
338
|
// ---------------------------------------------------------------- configuration
|
|
316
339
|
|
|
@@ -321,22 +344,84 @@ export function pathsFor(identityFile) {
|
|
|
321
344
|
}
|
|
322
345
|
|
|
323
346
|
/**
|
|
324
|
-
* Where relay "host[:port]" is reached: MQTT over TLS on port (8883), HTTPS on 443
|
|
325
|
-
* { [relay]: { mqtt, http } } overrides, e.g. a relay
|
|
326
|
-
*
|
|
347
|
+
* Where relay "host[:port]" is reached: MQTT over TLS on port (8883), HTTPS on 443, MQTT over
|
|
348
|
+
* WebSocket at wss://host/mqtt. endpoints: { [relay]: { mqtt, http, ws? } } overrides, e.g. a relay
|
|
349
|
+
* on loopback: mqtt may be mqtts:// or wss://, ws wss:// (by default the http origin at /mqtt);
|
|
350
|
+
* plain mqtt://, ws:// and http:// only to a loopback address, so nothing leaves the machine in clear.
|
|
327
351
|
*/
|
|
328
352
|
export function endpointOf(relay, endpoints = {}) {
|
|
329
353
|
const o = endpoints && Object.hasOwn(endpoints, relay) ? endpoints[relay] : null;
|
|
330
354
|
if (!o) {
|
|
331
355
|
const [host, port] = relay.split(':');
|
|
332
|
-
return { mqtt: `mqtts://${host}:${port ?? MQTT_PORT}`, http: `https://${host}` };
|
|
356
|
+
return { mqtt: `mqtts://${host}:${port ?? MQTT_PORT}`, http: `https://${host}`, ws: `wss://${host}${WS_PATH}` };
|
|
333
357
|
}
|
|
334
|
-
|
|
358
|
+
const check = (k, ok) => {
|
|
335
359
|
let u;
|
|
336
360
|
try { u = new URL(o[k]); } catch { fail('relay', `${relay}: endpoints.${k} is not a URL`); }
|
|
337
|
-
|
|
361
|
+
const [secure, plain] = ok.find(([sec, pl]) => u.protocol === sec || u.protocol === pl) ?? ok[0];
|
|
362
|
+
if (u.protocol !== secure && !(u.protocol === plain && LOOPBACK.has(u.hostname))) fail('relay', `${relay}: endpoints.${k} must be ${ok.map(([x]) => `${x}//`).join(' or ')} (${ok.map(([, x]) => `${x}//`).join(' or ')} only to a loopback address)`);
|
|
363
|
+
};
|
|
364
|
+
check('mqtt', [['mqtts:', 'mqtt:'], ['wss:', 'ws:']]);
|
|
365
|
+
check('http', [['https:', 'http:']]);
|
|
366
|
+
const http = o.http.replace(/\/+$/, '');
|
|
367
|
+
if (o.ws !== undefined) check('ws', [['wss:', 'ws:']]);
|
|
368
|
+
return { mqtt: o.mqtt, http, ws: o.ws ?? http.replace(/^http/, 'ws') + WS_PATH };
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* The HTTP CONNECT proxy for url (https: or wss:), from HTTPS_PROXY or https_proxy, unless NO_PROXY
|
|
373
|
+
* (or no_proxy) names its host: "*", a name (its subdomains too; a leading "." or "*." the same), an
|
|
374
|
+
* address, each with an optional :port. → a URL, or null. Only an http:// proxy; TLS to the relay
|
|
375
|
+
* runs inside the tunnel, verified as without one (NODE_EXTRA_CA_CERTS included).
|
|
376
|
+
*/
|
|
377
|
+
export function proxyFor(url, env = process.env) {
|
|
378
|
+
const u = new URL(url);
|
|
379
|
+
const raw = env.HTTPS_PROXY || env.https_proxy;
|
|
380
|
+
if ((u.protocol !== 'https:' && u.protocol !== 'wss:') || !raw) return null;
|
|
381
|
+
const host = u.hostname.replace(/^\[|\]$/g, '').toLowerCase(), port = u.port || '443';
|
|
382
|
+
for (const e of String(env.NO_PROXY || env.no_proxy || '').toLowerCase().split(/[\s,]+/).filter(Boolean)) {
|
|
383
|
+
if (e === '*') return null;
|
|
384
|
+
const m = /^\[([^\]]+)\](?::(\d+))?$/.exec(e) ?? (e.split(':').length === 2 ? /^([^:]+):(\d+)$/.exec(e) : null);
|
|
385
|
+
const name = (m ? m[1] : e).replace(/^\*?\./, '.'), p = m?.[2];
|
|
386
|
+
if (p && p !== port) continue;
|
|
387
|
+
if (name.startsWith('.') ? host.endsWith(name) || host === name.slice(1) : host === name || host.endsWith(`.${name}`)) return null;
|
|
388
|
+
}
|
|
389
|
+
let p;
|
|
390
|
+
try { p = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `http://${raw}`); } catch { fail('connect', 'HTTPS_PROXY is not a URL: want http://host:port'); }
|
|
391
|
+
if (p.protocol !== 'http:') fail('connect', `HTTPS_PROXY: ${p.protocol}// proxies are not supported; want http://host:port (HTTP CONNECT)`);
|
|
392
|
+
return p;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// An https.Agent whose every connection is a tunnel through proxy (HTTP CONNECT host:port), with
|
|
396
|
+
// TLS to the relay inside it: for the HTTP calls (http) and for MQTT over WebSocket (ws's agent).
|
|
397
|
+
class Tunnel extends HttpsAgent {
|
|
398
|
+
constructor(proxy) { super({ keepAlive: false }); this.proxy = proxy; }
|
|
399
|
+
createConnection(options, cb) {
|
|
400
|
+
const p = this.proxy, host = options.host.includes(':') ? `[${options.host}]` : options.host, target = `${host}:${options.port || 443}`;
|
|
401
|
+
const auth = p.username ? { 'proxy-authorization': `Basic ${Buffer.from(`${decodeURIComponent(p.username)}:${decodeURIComponent(p.password)}`).toString('base64')}` } : {};
|
|
402
|
+
const req = httpRequest({ host: p.hostname.replace(/^\[|\]$/g, ''), port: p.port || 80, method: 'CONNECT', path: target, agent: false, headers: { host: target, ...auth } });
|
|
403
|
+
req.setTimeout(HTTP_MS, () => req.destroy(new Error(`no answer within ${HTTP_MS / 1000} s`)));
|
|
404
|
+
req.once('connect', (res, sock) => {
|
|
405
|
+
req.setTimeout(0);
|
|
406
|
+
if (res.statusCode !== 200) { sock.destroy(); return cb(new Error(`the proxy ${p.host} answered ${res.statusCode} to CONNECT ${target}`)); }
|
|
407
|
+
cb(null, tlsConnect({ ...options, socket: sock, servername: options.servername || options.host }));
|
|
408
|
+
});
|
|
409
|
+
req.once('error', (e) => cb(new Error(`the proxy ${p.host}: ${e.code ?? e.message}`)));
|
|
410
|
+
req.end();
|
|
338
411
|
}
|
|
339
|
-
|
|
412
|
+
}
|
|
413
|
+
const tunnelFor = (url) => { const p = proxyFor(url); return p ? new Tunnel(p) : null; };
|
|
414
|
+
|
|
415
|
+
// An HTTPS request through a tunnel, answered in the shape of fetch's Response as http() reads it.
|
|
416
|
+
function viaTunnel(url, init, agent) {
|
|
417
|
+
return new Promise((resolve, reject) => {
|
|
418
|
+
const body = init.body === undefined ? undefined : Buffer.from(init.body);
|
|
419
|
+
const req = httpsRequest(url, { method: init.method ?? 'GET', agent, signal: init.signal, headers: body ? { 'content-type': 'text/plain;charset=UTF-8', 'content-length': body.length } : {} }, (res) => {
|
|
420
|
+
resolve({ status: res.statusCode, type: 'basic', body: res, headers: { get: (k) => { const v = res.headers[k.toLowerCase()]; return v === undefined ? null : String(v); } } });
|
|
421
|
+
});
|
|
422
|
+
req.once('error', (e) => reject(Object.assign(new Error(e.message), { cause: e })));
|
|
423
|
+
req.end(body);
|
|
424
|
+
});
|
|
340
425
|
}
|
|
341
426
|
|
|
342
427
|
/**
|
|
@@ -362,7 +447,7 @@ export function retentionOf(info) {
|
|
|
362
447
|
return retentionOk(n) ? n : null;
|
|
363
448
|
}
|
|
364
449
|
|
|
365
|
-
/** SIGELO_RELAY (the relay new invites name), SIGELO_RELAY_ENDPOINTS (JSON, as endpointOf), SIGELO_RELAY_RETENTION_DAYS. */
|
|
450
|
+
/** SIGELO_RELAY (the relay new invites name), SIGELO_RELAY_ENDPOINTS (JSON, as endpointOf), SIGELO_RELAY_RETENTION_DAYS, SIGELO_RELAY_TRANSPORT. */
|
|
366
451
|
export function optionsFromEnv(env = process.env) {
|
|
367
452
|
const o = {};
|
|
368
453
|
if (env.SIGELO_RELAY) o.relay = env.SIGELO_RELAY;
|
|
@@ -374,6 +459,10 @@ export function optionsFromEnv(env = process.env) {
|
|
|
374
459
|
if (!retentionOk(n)) fail('relay', `SIGELO_RELAY_RETENTION_DAYS: whole days, 1 to ${RETENTION_MAX_DAYS} (the reader's tier)`);
|
|
375
460
|
o.retentionDays = n;
|
|
376
461
|
}
|
|
462
|
+
if (env.SIGELO_RELAY_TRANSPORT) {
|
|
463
|
+
if (!TRANSPORTS.includes(env.SIGELO_RELAY_TRANSPORT)) fail('relay', `SIGELO_RELAY_TRANSPORT: ${TRANSPORTS.join(', ')} (MQTT over TLS on 8883, over WebSocket on 443, or the first then the second)`);
|
|
464
|
+
o.transport = env.SIGELO_RELAY_TRANSPORT;
|
|
465
|
+
}
|
|
377
466
|
return o;
|
|
378
467
|
}
|
|
379
468
|
|
|
@@ -580,7 +669,10 @@ async function http(url, init = {}) {
|
|
|
580
669
|
let res;
|
|
581
670
|
const at = where(url), http = { url, method: init.method ?? 'GET' };
|
|
582
671
|
const t0 = Date.now();
|
|
583
|
-
try {
|
|
672
|
+
try {
|
|
673
|
+
const agent = tunnelFor(url);
|
|
674
|
+
res = agent ? await viaTunnel(url, { ...init, signal: AbortSignal.timeout(HTTP_MS) }, agent) : await fetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(HTTP_MS) });
|
|
675
|
+
} catch (e) {
|
|
584
676
|
const why = e.name === 'TimeoutError' ? `no answer within ${HTTP_MS / 1000} s` : e.cause?.code ?? e.cause?.message ?? e.message;
|
|
585
677
|
fail('connect', `cannot reach the relay at ${at} (${why}): check the network and SIGELO_RELAY / SIGELO_RELAY_ENDPOINTS, then try again`, { cause: e, http });
|
|
586
678
|
}
|
|
@@ -588,7 +680,7 @@ async function http(url, init = {}) {
|
|
|
588
680
|
// The relay's clock (Date, whole seconds) and the round trip to it, for clockOffset.
|
|
589
681
|
const rtt = Date.now() - t0, date = Date.parse(res.headers.get('date') ?? '');
|
|
590
682
|
if ((res.status >= 300 && res.status < 400) || res.type === 'opaqueredirect') {
|
|
591
|
-
try { await res.body?.cancel(); } catch {}
|
|
683
|
+
try { await (res.body?.cancel?.() ?? res.body?.destroy?.()); } catch {}
|
|
592
684
|
fail('connect', `${at}: answered ${res.status}, a redirect, which this client does not follow`, { http });
|
|
593
685
|
}
|
|
594
686
|
if (Number(res.headers.get('content-length') ?? 0) > HTTP_MAX) fail('connect', `${at}: answer over ${HTTP_MAX} bytes`, { http });
|
|
@@ -647,6 +739,12 @@ export function keepLong(e, long) {
|
|
|
647
739
|
return k;
|
|
648
740
|
}
|
|
649
741
|
|
|
742
|
+
// Whose quota a quota_storage refusal is (relay/allowance.mjs `side`), in this client's words: a
|
|
743
|
+
// contact whose own queue is full, or whose operator's Pro lapsed, must not read as a broken relay.
|
|
744
|
+
const QUOTA_SIDES = new Set(['reader', 'sender', 'relay']);
|
|
745
|
+
const quotaWhy = (r, name) => (r.code !== 'quota_storage' ? null
|
|
746
|
+
: r.side === 'reader' ? `${name}'s side is over its storage quota (its queue is full, or its operator's Pro lapsed): nothing is wrong with your relay or your allowance; send again once ${name}'s agent has collected its messages (${relaySays(r.detail)})`
|
|
747
|
+
: r.side === 'sender' ? `your network has used its share of this relay's free storage: send again once messages are collected or expire (${relaySays(r.detail)})` : null);
|
|
650
748
|
// Text a relay writes reaches the operator, and perhaps a model, inside this client's messages:
|
|
651
749
|
// quoted and cut short, so it reads as data.
|
|
652
750
|
const relaySays = (s) => `the relay says ${JSON.stringify(String(s ?? '').slice(0, 200))}`;
|
|
@@ -720,10 +818,13 @@ export function limitPackets(stream, max, cut) {
|
|
|
720
818
|
});
|
|
721
819
|
}
|
|
722
820
|
|
|
723
|
-
|
|
821
|
+
// url: mqtts://, or wss:// (MQTT over WebSocket: through the HTTPS proxy when one applies, proxyFor;
|
|
822
|
+
// a frame over the largest packet, its fixed header included, refused by ws before it is held).
|
|
823
|
+
function mqttConnect(url, creds, link, onPacket, timeout = CONNECT_MS) {
|
|
724
824
|
return new Promise((resolve, reject) => {
|
|
825
|
+
const agent = /^wss?:/.test(url) ? tunnelFor(url) : null;
|
|
725
826
|
const client = connect(url, { protocolVersion: 4, clean: false, clientId: creds.clientId, username: creds.username, password: Buffer.from(creds.password, 'utf8'),
|
|
726
|
-
reconnectPeriod: 0, connectTimeout:
|
|
827
|
+
reconnectPeriod: 0, connectTimeout: timeout, keepalive: 60, resubscribe: false, wsOptions: { maxPayload: MAX_PACKET + 5, perMessageDeflate: false, ...(agent && { agent }) } });
|
|
727
828
|
link.client = client;
|
|
728
829
|
// connect() has built the socket and nothing has arrived yet. The cut is permanent at a relay
|
|
729
830
|
// other than this agent's own (#retry, accept): it would send the same packet again.
|
|
@@ -743,6 +844,25 @@ function mqttConnect(url, creds, link, onPacket) {
|
|
|
743
844
|
});
|
|
744
845
|
}
|
|
745
846
|
|
|
847
|
+
// transport "auto": the WebSocket endpoint each MQTT endpoint fell back to, for the process lifetime,
|
|
848
|
+
// so a reconnection does not wait on 8883 first.
|
|
849
|
+
const FELL_BACK = new Map();
|
|
850
|
+
// The WebSocket endpoint of ep: relay.json's endpoints.mqtt_ws when it names the same host as ep.http
|
|
851
|
+
// over wss:// (ws:// only to loopback), else ep.ws. A relay that could name any host would send the
|
|
852
|
+
// login to it. Asked once per process and relay.
|
|
853
|
+
const WS_INFO = new Map();
|
|
854
|
+
async function wsEndpoint(ep) {
|
|
855
|
+
if (!WS_INFO.has(ep.http)) {
|
|
856
|
+
let url = ep.ws;
|
|
857
|
+
try {
|
|
858
|
+
const r = await http(`${ep.http}/relay.json`), w = new URL(r.body?.endpoints?.mqtt_ws), h = new URL(ep.http);
|
|
859
|
+
if (r.status === 200 && w.hostname === h.hostname && (w.protocol === 'wss:' || (w.protocol === 'ws:' && LOOPBACK.has(w.hostname)))) url = w.href;
|
|
860
|
+
} catch {}
|
|
861
|
+
WS_INFO.set(ep.http, url);
|
|
862
|
+
}
|
|
863
|
+
return WS_INFO.get(ep.http);
|
|
864
|
+
}
|
|
865
|
+
|
|
746
866
|
class Link {
|
|
747
867
|
constructor(relay, own) {
|
|
748
868
|
this.relay = relay; this.own = own; this.client = null; this.subscribed = new Set(); this.refused = new Map(); // topic → when refused
|
|
@@ -775,8 +895,10 @@ export class Carrier {
|
|
|
775
895
|
#mineMemo = null; #clocks = new Map();
|
|
776
896
|
|
|
777
897
|
constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
|
|
778
|
-
onEvent, keep, backoff = BACKOFF, tick = TICK, files }) {
|
|
779
|
-
if (
|
|
898
|
+
onEvent, keep, backoff = BACKOFF, tick = TICK, files, transport = 'auto' }) {
|
|
899
|
+
if (!TRANSPORTS.includes(transport)) throw new TypeError(`transport: ${TRANSPORTS.join(', ')}`);
|
|
900
|
+
this.transport = transport;
|
|
901
|
+
if (typeof identity !== 'function') throw new TypeError('identity: a function returning { sign, bundle }');
|
|
780
902
|
if (typeof store !== 'string' || typeof state !== 'string') throw new TypeError('store, state: file paths (pathsFor(identityFile))');
|
|
781
903
|
if (retentionDays !== undefined && !retentionOk(retentionDays)) throw new TypeError(`retentionDays: 1 to ${RETENTION_MAX_DAYS}`);
|
|
782
904
|
// Not given: relay.json's at the first login to this agent's own relay may set it (#relayInfo).
|
|
@@ -793,9 +915,10 @@ export class Carrier {
|
|
|
793
915
|
|
|
794
916
|
// ---- files, under the lock
|
|
795
917
|
|
|
796
|
-
// The identity as of now: original and current DID, the current genesis and
|
|
918
|
+
// The identity as of now: original and current DID, the current genesis, and sign(body), the
|
|
919
|
+
// only way anything here signs as it.
|
|
797
920
|
#me(now) {
|
|
798
|
-
const
|
|
921
|
+
const id = this.identity(), { bundle } = id, sign = (body) => signAs(id, body);
|
|
799
922
|
let r;
|
|
800
923
|
try { r = verify(chainOf(bundle), now); } catch (e) { fail('identity', `this agent's bundle does not verify: ${e.message}`); }
|
|
801
924
|
const genesis = [bundle.genesis, ...bundle.rotations.map((x) => x.next_genesis)].find((g) => didOf(g) === r.did);
|
|
@@ -805,7 +928,7 @@ export class Carrier {
|
|
|
805
928
|
for (let i = 0; i + 1 < r.chain.length; i++) {
|
|
806
929
|
if (bundle.rotations.some((x) => x.body.id === r.chain[i] && x.body.next === r.chain[i + 1] && x.body.reason === 'recovery')) recovery = i;
|
|
807
930
|
}
|
|
808
|
-
return { did: r.chain[0], current_did: r.did,
|
|
931
|
+
return { did: r.chain[0], current_did: r.did, sign, genesis, bundle, chain: r.chain, recovery };
|
|
809
932
|
}
|
|
810
933
|
|
|
811
934
|
// The state is saved before the store's held writes (store.mjs hold: a handshake's), so a crash
|
|
@@ -896,7 +1019,7 @@ export class Carrier {
|
|
|
896
1019
|
#restore(st, store, me, did) {
|
|
897
1020
|
const c = store.lookup(did);
|
|
898
1021
|
if (!c || c.revoked || !c.pair_key) return null;
|
|
899
|
-
const s = session({ me: { did: me.did, current_did: me.current_did,
|
|
1022
|
+
const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K: hexToBytes(c.pair_key), hold: this.retention });
|
|
900
1023
|
const d = st.peers[c.did]?.session;
|
|
901
1024
|
// A session of an earlier pairing key belongs to a pairing that was replaced: start afresh.
|
|
902
1025
|
if (d && d.pair === s.pair) loadSession(s, d);
|
|
@@ -1091,7 +1214,7 @@ export class Carrier {
|
|
|
1091
1214
|
let n;
|
|
1092
1215
|
try { n = parseBytes(bytes); } catch { return; }
|
|
1093
1216
|
if (n === null || typeof n !== 'object' || typeof n.code !== 'string') return;
|
|
1094
|
-
const note = { code: n.code.slice(0, 64), detail: typeof n.detail === 'string' ? n.detail.slice(0, 200) : '' };
|
|
1217
|
+
const note = { code: n.code.slice(0, 64), detail: typeof n.detail === 'string' ? n.detail.slice(0, 200) : '', ...(QUOTA_SIDES.has(n.side) && { side: n.side }) };
|
|
1095
1218
|
// id: the packet id of the PUBLISH a refusal names (#publish), kept out of events.
|
|
1096
1219
|
if (link.collect) link.collect.push(Number.isSafeInteger(n.id) ? { ...note, id: n.id } : note);
|
|
1097
1220
|
else this.#emit({ type: 'notice', relay: link.relay, ...note });
|
|
@@ -1499,9 +1622,9 @@ export class Carrier {
|
|
|
1499
1622
|
const c = store.lookup(res.did), K = hexToBytes(res.pair_key);
|
|
1500
1623
|
// What checkAnswer replaced, put back if the reply cannot reach the answerer (#unpair).
|
|
1501
1624
|
const undo = { contact: before[c.did] ?? null, peer: st.peers[c.did] ?? null };
|
|
1502
|
-
const s = session({ me: { did: me.did, current_did: me.current_did,
|
|
1503
|
-
const prekeys = s.in.prekeys.issue({ current_did: me.current_did,
|
|
1504
|
-
const reply = buildReply({ answer_id: res.answer_id, identity: {
|
|
1625
|
+
const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K });
|
|
1626
|
+
const prekeys = s.in.prekeys.issue({ current_did: me.current_did, sign: me.sign }, s.pair, now);
|
|
1627
|
+
const reply = buildReply({ answer_id: res.answer_id, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_ct: ct, prekeys });
|
|
1505
1628
|
const frame = seal(KIND.invite_reply, keys.key, keys.reply_topic, reply);
|
|
1506
1629
|
const entry = { relay: p.relay, topic: keys.reply_topic, kind: KIND.invite_reply, control: 'reply', peer: c.did, undo,
|
|
1507
1630
|
needs: [topic(K, c.did, me.did, isoWeek(now))], exp: p.exp };
|
|
@@ -1575,7 +1698,7 @@ export class Carrier {
|
|
|
1575
1698
|
// An entry written before `as` was kept: unknown, so the notice goes (#next `first`).
|
|
1576
1699
|
const answered = waiting.find(([x]) => x === id)[1], held = answered.as ?? null;
|
|
1577
1700
|
const c = renamed(store, store.lookup(res.did), answered);
|
|
1578
|
-
const s = session({ me: { did: me.did, current_did: me.current_did,
|
|
1701
|
+
const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K: hexToBytes(res.pair_key) });
|
|
1579
1702
|
const events = [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key) })];
|
|
1580
1703
|
try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
|
|
1581
1704
|
if (!(e instanceof MsgError)) throw e;
|
|
@@ -1647,7 +1770,7 @@ export class Carrier {
|
|
|
1647
1770
|
e.announced = me.current_did;
|
|
1648
1771
|
e.noticed = now;
|
|
1649
1772
|
e.notice_asked = false;
|
|
1650
|
-
return this.#queue(st, { relay, topic: t, bytes: seal(KIND_NOTICE, noticeKey(K, me.did, c.did), t, { bundle: chainOf(me.bundle), proof: { body: proof, sig: sign(
|
|
1773
|
+
return this.#queue(st, { relay, topic: t, bytes: seal(KIND_NOTICE, noticeKey(K, me.did, c.did), t, { bundle: chainOf(me.bundle), proof: { body: proof, sig: me.sign(proof) } }),
|
|
1651
1774
|
kind: KIND_NOTICE, peer: c.did, control: 'notice' });
|
|
1652
1775
|
}
|
|
1653
1776
|
if (c.re_pair) {
|
|
@@ -1794,7 +1917,7 @@ export class Carrier {
|
|
|
1794
1917
|
const back = r?.code === 'no_reader' && e.kind === KIND.message && e.item !== undefined;
|
|
1795
1918
|
if (e.control === undefined || e.control === 'answer') this.#results.set(e.id, back ? { code: null, queued: noReader(this.#nameOf(e.peer)) } : r ?? { code: null }); // what a verb waits for
|
|
1796
1919
|
this.#emit(back ? { type: 'queued', id: e.id, peer: e.peer, code: r.code, detail: r.detail }
|
|
1797
|
-
: r ? { type: 'refused', id: e.id, peer: e.peer, control: e.control, code: r.code, detail: r.detail } : { type: 'sent', id: e.id, peer: e.peer, control: e.control });
|
|
1920
|
+
: r ? { type: 'refused', id: e.id, peer: e.peer, control: e.control, code: r.code, ...(r.side && { side: r.side }), detail: r.detail } : { type: 'sent', id: e.id, peer: e.peer, control: e.control });
|
|
1798
1921
|
// A refusal stops this round: what follows would be refused alike (a quota, the rate brake),
|
|
1799
1922
|
// and a control frame would be queued again at once. The next round retries. A mailbox
|
|
1800
1923
|
// nobody holds stops only what goes to that contact (absent, #next).
|
|
@@ -1931,7 +2054,7 @@ export class Carrier {
|
|
|
1931
2054
|
if (ch.relay !== relay) fail('challenge', `relay ${JSON.stringify(ch.relay)} is not this relay's name, ${relay}`);
|
|
1932
2055
|
// Signed as built here, never as received; its typ is one no challenge signer produces (a SPEC
|
|
1933
2056
|
// §5.2 challenge for this relay, got by a world from sign-challenge, logs in nobody).
|
|
1934
|
-
const body = { v: LOGIN_V, typ: TYP_LOGIN, did: me.current_did, relay, nonce: ch.nonce }, sig = sign(
|
|
2057
|
+
const body = { v: LOGIN_V, typ: TYP_LOGIN, did: me.current_did, relay, nonce: ch.nonce }, sig = me.sign(body);
|
|
1935
2058
|
if (!verifySig(me.genesis.key, body, sig)) fail('identity', 'this agent\'s secret does not match its current genesis key');
|
|
1936
2059
|
if (canonicalize(body) !== canonicalize(ch)) fail('challenge', 'not the login body this agent signs');
|
|
1937
2060
|
let pow;
|
|
@@ -2004,8 +2127,21 @@ export class Carrier {
|
|
|
2004
2127
|
const info = link.own && this.#ask ? this.#relayInfo(ep) : null;
|
|
2005
2128
|
const creds = await this.#credentials(relay, ep);
|
|
2006
2129
|
await info;
|
|
2130
|
+
// The transport (the header's "Transport"): auto tries ep.mqtt for PROBE_MS, then the WebSocket
|
|
2131
|
+
// endpoint, and keeps to it for the rest of the process (FELL_BACK). Only a dial that got no
|
|
2132
|
+
// CONNACK at all falls back: a refusal by name (its return code) is the relay's answer, on
|
|
2133
|
+
// either transport. Both are TLS; nothing falls back to a plain connection.
|
|
2134
|
+
const onPacket = (packet) => this.#onPacket(link, packet);
|
|
2135
|
+
const probe = this.transport === 'auto' && !FELL_BACK.has(ep.mqtt) && /^mqtts?:/.test(ep.mqtt);
|
|
2136
|
+
let url = this.transport === 'wss' ? await wsEndpoint(ep) : this.transport === 'auto' ? FELL_BACK.get(ep.mqtt) ?? ep.mqtt : ep.mqtt;
|
|
2007
2137
|
// A cut connection is this client's own refusal: no POST /check may rename it.
|
|
2008
|
-
try { await mqttConnect(
|
|
2138
|
+
try { await mqttConnect(url, creds, link, onPacket, probe ? PROBE_MS : CONNECT_MS); } catch (e) {
|
|
2139
|
+
if (!probe || link.cut || typeof e.code === 'number') throw link.cut ?? await named(ep, creds, e);
|
|
2140
|
+
url = await wsEndpoint(ep);
|
|
2141
|
+
try { await mqttConnect(url, creds, link, onPacket); } catch (e2) { throw link.cut ?? await named(ep, creds, e2); }
|
|
2142
|
+
FELL_BACK.set(ep.mqtt, url);
|
|
2143
|
+
this.#emit({ type: 'transport', relay, transport: 'wss', detail: `${ep.mqtt} gave no CONNACK within ${PROBE_MS / 1000} s (${e.message}): MQTT over WebSocket at ${url} for the rest of this process` });
|
|
2144
|
+
}
|
|
2009
2145
|
// A close right after CONNACK (a cut in the same read) reached no listener of this connection.
|
|
2010
2146
|
if (!link.client.connected) throw link.cut ?? new MsgError('connect', 'the relay closed the connection');
|
|
2011
2147
|
// Deliveries are counted from here (quiet), not from before the login: a proof-of-work search
|
|
@@ -2185,6 +2321,25 @@ export class Carrier {
|
|
|
2185
2321
|
return r.body.invite;
|
|
2186
2322
|
}
|
|
2187
2323
|
|
|
2324
|
+
// A gift code redeemed at this agent's own relay (POST /gift, relay/gifts.mjs): the relay gets the
|
|
2325
|
+
// code's hash (short.mjs giftHash), never the code, with a login of its own; the identity logged
|
|
2326
|
+
// in becomes the operator whose pool is Pro. A malformed code is refused here, before any login.
|
|
2327
|
+
async redeemGift(text) {
|
|
2328
|
+
const hash = giftHash(text), ep = endpointOf(this.relay, this.endpoints);
|
|
2329
|
+
const creds = await this.#credentials(this.relay, ep);
|
|
2330
|
+
const r = await http(`${ep.http}/gift`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, code_hash: hash }) });
|
|
2331
|
+
this.#clockFrom(this.relay, r);
|
|
2332
|
+
const check = typeof r.body?.check === 'string' ? r.body.check : null;
|
|
2333
|
+
if (r.status === 429) refuse('rate', `the relay ${this.relay} takes no more gift codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to an hour')}`, r);
|
|
2334
|
+
if ((r.status === 404 || r.status === 405) && check === null) refuse('gift', `the relay ${this.relay} takes no gift codes`, r);
|
|
2335
|
+
if (r.status !== 200) refuse('connect', `${this.relay}: ${statusWhy(r, 'POST /gift')}`, r);
|
|
2336
|
+
if (r.body?.ok !== true) refuse(GIFT_CHECKS.has(check) ? check : 'gift', `the relay refused the gift code (${relaySays(`${check}: ${r.body?.detail}`)})`, r);
|
|
2337
|
+
// A proof sent with this login was taken: the identity is stored there now, as after a session.
|
|
2338
|
+
if (creds.pow !== undefined) this.#locked(({ st }) => { (st.relays[this.relay] ??= { proven: false, claims: {} }).proven = true; });
|
|
2339
|
+
if (!Number.isSafeInteger(r.body.exp) || !Number.isSafeInteger(r.body.months)) refuse('connect', `${this.relay}: POST /gift answered ok without the new expiry: SIGELO_DEBUG=1 shows the answer`, r);
|
|
2340
|
+
return { exp: r.body.exp, months: r.body.months };
|
|
2341
|
+
}
|
|
2342
|
+
|
|
2188
2343
|
async accept(text, opts = {}) {
|
|
2189
2344
|
// Short or long by the input's shape, before either parser runs (short.mjs codeKind).
|
|
2190
2345
|
const how = codeKind(text) === 'short' ? 'parked' : 'long';
|
|
@@ -2203,7 +2358,7 @@ export class Carrier {
|
|
|
2203
2358
|
}
|
|
2204
2359
|
const k = kemKey();
|
|
2205
2360
|
try {
|
|
2206
|
-
const answer = buildAnswer({ code, identity: {
|
|
2361
|
+
const answer = buildAnswer({ code, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_pk: k.pk, prekeys: null });
|
|
2207
2362
|
const keys = inviteKeys(code.secret), frame = seal(KIND.invite_answer, keys.key, keys.answer_topic, answer);
|
|
2208
2363
|
// Checked before anything is stored: the relay would refuse it (quota_storage).
|
|
2209
2364
|
if (frame.length > INVITE_BYTES) fail('too_large', `the answer is ${frame.length} bytes, more than an invite topic holds (${INVITE_BYTES}): this agent's chain is too long`);
|
|
@@ -2306,7 +2461,8 @@ export class Carrier {
|
|
|
2306
2461
|
|
|
2307
2462
|
async send(to, content, { label = '', local = false } = {}) {
|
|
2308
2463
|
const [r] = await this.sendAll(to, [content], { label, local });
|
|
2309
|
-
|
|
2464
|
+
// side: whose quota a quota_storage is (relay/allowance.mjs), on the error too.
|
|
2465
|
+
if (r.status === 'refused') throw Object.assign(new MsgError(r.code, `refused (${r.detail})`), r.side && { side: r.side });
|
|
2310
2466
|
return r;
|
|
2311
2467
|
}
|
|
2312
2468
|
|
|
@@ -2358,7 +2514,7 @@ export class Carrier {
|
|
|
2358
2514
|
const r = this.#results.get(id);
|
|
2359
2515
|
this.#results.delete(id);
|
|
2360
2516
|
// detail: the carrier's own words when it refused the message itself, else the relay's, quoted.
|
|
2361
|
-
if (r?.code) return { status: 'refused', id, to: c.did, name: c.name, code: r.code, detail: r.local ? r.detail : relaySays(r.detail) };
|
|
2517
|
+
if (r?.code) return { status: 'refused', id, to: c.did, name: c.name, code: r.code, ...(r.side && { side: r.side }), detail: r.local ? r.detail : quotaWhy(r, c.name) ?? relaySays(r.detail) };
|
|
2362
2518
|
if (!r || r.queued) return { status: 'queued', id, to: c.did, name: c.name, detail: r?.queued ?? 'waiting for the relay\'s acknowledgement: it goes at the next connection' };
|
|
2363
2519
|
return { status: 'sent', id, to: c.did, name: c.name };
|
|
2364
2520
|
});
|
package/enrol.mjs
CHANGED
|
@@ -49,10 +49,10 @@ import { hkdf } from '@noble/hashes/hkdf.js';
|
|
|
49
49
|
import { hmac } from '@noble/hashes/hmac.js';
|
|
50
50
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
51
51
|
import { bytesToHex, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
52
|
-
import {
|
|
52
|
+
import { canonicalize, decodeKey, did as didOf, keygen, rotate, sign, structure, verify, verifySig } from 'sigelo';
|
|
53
53
|
import { agentIdentitySeed, identitySeed, recoveryCommitment } from 'sigelo/dist/keys.js';
|
|
54
54
|
import { keepLong, readCode } from './carrier.mjs';
|
|
55
|
-
import { MsgError, checkNow, fail, pairId, unhex } from './kdf.mjs';
|
|
55
|
+
import { MsgError, checkNow, fail, pairId, signAs, unhex } from './kdf.mjs';
|
|
56
56
|
import { codeKind } from './short.mjs';
|
|
57
57
|
|
|
58
58
|
export const ENROL_V = 'sigelo-enrol/1';
|
|
@@ -100,10 +100,14 @@ export function operatorIdentity(S, n) {
|
|
|
100
100
|
return { v: 'sigelo/0', secret: bytesToHex(c.secret), genesis: c.genesis, rotations: c.rotations, attestations: [], issuers: [], derived: { path: `${IDENTITY_PATH}/${n}`, n } };
|
|
101
101
|
}
|
|
102
102
|
/** The operator attestation for a worker (relay/operator.mjs's shape), sub its ORIGINAL DID. */
|
|
103
|
-
|
|
103
|
+
// Signed by sign (the operator's signer, sigelo-agent-keys.ts) or secret (kdf.mjs signAs); the body
|
|
104
|
+
// is the one sigelo's attest() builds.
|
|
105
|
+
export function operatorAttestation({ sign: signer, secret, iss, sub, relay, now, days = OPERATOR_DAYS }) {
|
|
104
106
|
checkNow(now);
|
|
105
107
|
if (!Number.isSafeInteger(days) || days < 1 || days > OPERATOR_DAYS) fail('enrol', `days: 1 to ${OPERATOR_DAYS}`);
|
|
106
|
-
|
|
108
|
+
const body = { v: 'sigelo/0', typ: 'attestation', iss, sub, iat: now, exp: now + days * DAY, ctx: OPERATOR_CTX, admission: 'invite', claims: { relay }, admission_by: iss };
|
|
109
|
+
structure(body, 'attestation');
|
|
110
|
+
return { body, sig: signAs({ sign: signer, secret }, body) };
|
|
107
111
|
}
|
|
108
112
|
|
|
109
113
|
/** The identity file of worker i, rotation n, carrying the operator's attestation and genesis. */
|
|
@@ -218,12 +222,12 @@ const isObject = (x) => typeof x === 'object' && x !== null && !Array.isArray(x)
|
|
|
218
222
|
const nowOf = (carrier) => checkNow(carrier.clock());
|
|
219
223
|
const readStore = (carrier) => (existsSync(carrier.storePath) ? JSON.parse(readFileSync(carrier.storePath, 'utf8')) : { contacts: {} });
|
|
220
224
|
const pairOf = (c) => pairId(unhex(c.pair_key, 32, 'store'));
|
|
221
|
-
// The carrier's identity, verified: original DID, current DID and its genesis,
|
|
225
|
+
// The carrier's identity, verified: original DID, current DID and its genesis, and sign(body).
|
|
222
226
|
function self(carrier, now) {
|
|
223
|
-
const
|
|
227
|
+
const id = carrier.identity(), { bundle } = id;
|
|
224
228
|
const r = verify({ v: 'sigelo/0', typ: 'bundle', genesis: bundle.genesis, rotations: bundle.rotations, bindings: [], attestations: [], issuers: [] }, now);
|
|
225
229
|
const genesis = [bundle.genesis, ...bundle.rotations.map((x) => x.next_genesis)].find((g) => didOf(g) === r.did);
|
|
226
|
-
return { original: r.chain[0], did: r.did, genesis,
|
|
230
|
+
return { original: r.chain[0], did: r.did, genesis, sign: (body) => signAs(id, body) };
|
|
227
231
|
}
|
|
228
232
|
// The contact store record holding `did` in its chain, live and paired only.
|
|
229
233
|
const liveHolding = (carrier, did) => Object.values(readStore(carrier).contacts).find((c) => !c.revoked && c.pair_key && c.chain.includes(did)) ?? null;
|
|
@@ -243,7 +247,7 @@ export async function issue({ carrier, file, i, n, name, keeper }) {
|
|
|
243
247
|
// The temporary identity's contact, named apart from the worker's (forgotten once it has paired).
|
|
244
248
|
const r = await carrier.invite({ name: `${name ?? `worker ${i}`} (enrolling)`, short: true });
|
|
245
249
|
const now = nowOf(carrier), code = readCode(r.code, now), me = self(carrier, now);
|
|
246
|
-
const attestation = operatorAttestation({
|
|
250
|
+
const attestation = operatorAttestation({ sign: me.sign, iss: me.did, sub: w.original, relay: code.relay, now });
|
|
247
251
|
const old = liveHolding(carrier, w.original);
|
|
248
252
|
pending(file, now, (s) => {
|
|
249
253
|
s.issued[code.nonce] = { key: bytesToHex(enrolKey(code.secret)), i, n, name: name ?? null, did: w.did, original: w.original, old_pair: old ? pairOf(old) : null,
|
package/envelope.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// sigelo-msg/0 envelopes (design/relay-plan.md §3 "Envelope", §11 "Epoch recovery"): one
|
|
3
3
|
// end-to-end encrypted, signed message between two contacts, as the binary MQTT payload the relay
|
|
4
4
|
// stores. No network code.
|
|
5
|
-
// const s = session({ me, peer, K, hold }) me: { did, current_did, secret
|
|
5
|
+
// const s = session({ me, peer, K, hold }) me: { did, current_did, sign } (or secret: kdf.mjs signAs); peer: the store's contact record;
|
|
6
6
|
// hold: the longest the relay keeps an envelope for this reader
|
|
7
7
|
// acceptPrekeys(s, signedBundle, now) the contact's prekeys, checked (prekeys.mjs)
|
|
8
8
|
// send(s, { label, content }, now) → { bytes, topic, epoch, n, prekey, last_resort }
|
|
@@ -74,8 +74,8 @@
|
|
|
74
74
|
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
|
75
75
|
import { ml_kem768_x25519 as xwing } from '@noble/post-quantum/hybrid.js';
|
|
76
76
|
import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
77
|
-
import { canonicalize, parseBytes,
|
|
78
|
-
import { MSG_V, checkDid, checkNow, epochId, epochKey, fail, hex, isoWeek, pairId, step, topic, unhex } from './kdf.mjs';
|
|
77
|
+
import { canonicalize, parseBytes, verifySig } from 'sigelo';
|
|
78
|
+
import { MSG_V, checkDid, checkNow, epochId, epochKey, fail, hex, isoWeek, pairId, signAs, step, topic, unhex } from './kdf.mjs';
|
|
79
79
|
import { Prekeys, SKEW, checkPrekeys, exact } from './prekeys.mjs';
|
|
80
80
|
|
|
81
81
|
export const KIND = { message: 0, invite_answer: 1, invite_reply: 2, group: 3 };
|
|
@@ -311,7 +311,7 @@ export function send(s, { label, content }, now, rng = randomBytes) {
|
|
|
311
311
|
const slot = nextSlot(s, now, rng);
|
|
312
312
|
try {
|
|
313
313
|
const body = { v: MSG_V, typ: 'message', from: s.me.current_did, to: s.peer.did, pair: s.pair, epoch: hex(slot.epoch), n: slot.n, iat: now, label, content };
|
|
314
|
-
const r = seal(s, slot, { body, sig:
|
|
314
|
+
const r = seal(s, slot, { body, sig: signAs(s.me, body) }, now, rng);
|
|
315
315
|
slot.commit();
|
|
316
316
|
return r;
|
|
317
317
|
} catch (e) { slot.discard(); throw e; }
|
package/invite.mjs
CHANGED
|
@@ -10,8 +10,8 @@ import { randomBytes } from 'node:crypto';
|
|
|
10
10
|
import { hkdf } from '@noble/hashes/hkdf.js';
|
|
11
11
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
12
12
|
import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
13
|
-
import { canonicalize, did as didOf, multibase,
|
|
14
|
-
import { MsgError, pairKey } from './kdf.mjs';
|
|
13
|
+
import { canonicalize, did as didOf, multibase, verify, verifySig } from 'sigelo';
|
|
14
|
+
import { MsgError, pairKey, signAs } from './kdf.mjs';
|
|
15
15
|
|
|
16
16
|
export const V = 'sigelo-invite/0';
|
|
17
17
|
// Each side proves its key with a signed body of its own type, never a SPEC §5.2 challenge: an
|
|
@@ -180,13 +180,13 @@ function canonicalBundle(bundle) {
|
|
|
180
180
|
// { body: { v, typ, did: the signer's CURRENT DID, nonce, transcript }, sig }, signed "sigelo\n" ‖ JCS(body).
|
|
181
181
|
function prove(identity, typ, nonce, label, rest) {
|
|
182
182
|
const body = { v: V, typ, did: didOf(identity.genesis), nonce, transcript: attempt('card', () => digest(label, rest)) };
|
|
183
|
-
const sig =
|
|
183
|
+
const sig = signAs(identity, body);
|
|
184
184
|
if (!verifySig(identity.genesis.key, body, sig)) fail('identity', 'the secret does not match genesis.key');
|
|
185
185
|
return { body, sig };
|
|
186
186
|
}
|
|
187
187
|
|
|
188
188
|
/**
|
|
189
|
-
* Bob: the answer to a parsed code. identity = his CURRENT {
|
|
189
|
+
* Bob: the answer to a parsed code. identity = his CURRENT { sign, genesis } (or secret: kdf.mjs signAs); bundle = his bundle;
|
|
190
190
|
* kem_pk = his one-time hybrid public key, prekeys = his signed prekeys: both opaque here (M2).
|
|
191
191
|
* His proof binds the whole code (its nonce: the inviter it names, relay, expiry, secret) and every
|
|
192
192
|
* other member of the answer (transcript).
|
package/kdf.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import { hkdf } from '@noble/hashes/hkdf.js';
|
|
|
5
5
|
import { hmac } from '@noble/hashes/hmac.js';
|
|
6
6
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
7
7
|
import { bytesToHex, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
8
|
+
import { sign } from 'sigelo';
|
|
8
9
|
|
|
9
10
|
export const MSG_V = 'sigelo-msg/0';
|
|
10
11
|
|
|
@@ -21,6 +22,11 @@ export class MsgError extends Error {
|
|
|
21
22
|
}
|
|
22
23
|
export const fail = (check, why, extra) => { throw new MsgError(check, why, extra); };
|
|
23
24
|
|
|
25
|
+
// The identity's signature over a body ("sigelo\n" ‖ JCS(body), SPEC §3). me.sign is the signer the
|
|
26
|
+
// caller hands in (sigelo-agent-keys.ts: a plain file, a keychain, a key agent), so these modules
|
|
27
|
+
// never see where the key rests; me.secret, the seed itself, is what callers of 0.1.7 pass.
|
|
28
|
+
export const signAs = (me, body) => (typeof me.sign === 'function' ? me.sign(body) : sign(me.secret, body));
|
|
29
|
+
|
|
24
30
|
export const hex = (b) => bytesToHex(b);
|
|
25
31
|
export function unhex(s, len, check) {
|
|
26
32
|
if (typeof s !== 'string' || !new RegExp(`^[0-9a-f]{${len * 2}}$`).test(s)) fail(check, `expected ${len} bytes as lowercase hex`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sigelo-contact",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Agent contacts for sigelo identities: invite codes, a contact store, end-to-end encrypted envelopes with hybrid post-quantum key agreement, and an MQTT carrier. Client code (MIT); the relay server is csigelo/sigelo-relay (AGPL-3.0).",
|
|
6
6
|
"keywords": [
|
|
@@ -73,6 +73,7 @@
|
|
|
73
73
|
"test-envelope.mjs",
|
|
74
74
|
"test-file.mjs",
|
|
75
75
|
"test-tier.mjs",
|
|
76
|
+
"test-ws.mjs",
|
|
76
77
|
"test-invite.mjs",
|
|
77
78
|
"test-short.mjs"
|
|
78
79
|
],
|
|
@@ -80,7 +81,7 @@
|
|
|
80
81
|
"node": ">=22.18"
|
|
81
82
|
},
|
|
82
83
|
"scripts": {
|
|
83
|
-
"test": "node test-invite.mjs && node test-envelope.mjs && node test-carrier.mjs && node test-short.mjs && node test-file.mjs && node test-enrol.mjs && node test-tier.mjs",
|
|
84
|
+
"test": "node test-invite.mjs && node test-envelope.mjs && node test-carrier.mjs && node test-ws.mjs && node test-short.mjs && node test-file.mjs && node test-enrol.mjs && node test-tier.mjs",
|
|
84
85
|
"gen": "node gen-invite.mjs && node gen-envelope.mjs && node gen-carrier.mjs && node gen-short.mjs",
|
|
85
86
|
"prepack": "node ../release/prepack.mjs pre",
|
|
86
87
|
"postpack": "node ../release/prepack.mjs post",
|
|
@@ -91,6 +92,6 @@
|
|
|
91
92
|
"@noble/hashes": "^2.4.0",
|
|
92
93
|
"@noble/post-quantum": "^0.7.1",
|
|
93
94
|
"mqtt": "^5.16.0",
|
|
94
|
-
"sigelo": "^0.1.
|
|
95
|
+
"sigelo": "^0.1.8"
|
|
95
96
|
}
|
|
96
97
|
}
|
package/prekeys.mjs
CHANGED
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
// kept, the oldest going first.
|
|
22
22
|
import { ml_kem768_x25519 as xwing } from '@noble/post-quantum/hybrid.js';
|
|
23
23
|
import { randomBytes } from '@noble/hashes/utils.js';
|
|
24
|
-
import { canonicalize,
|
|
25
|
-
import { MSG_V, checkNow, fail, hex } from './kdf.mjs';
|
|
24
|
+
import { canonicalize, verifySig } from 'sigelo';
|
|
25
|
+
import { MSG_V, checkNow, fail, hex, signAs } from './kdf.mjs';
|
|
26
26
|
|
|
27
27
|
export const ONE_TIME = 20, REPLENISH_BELOW = 5, LAST_RESORT_DAYS = 30, TTL = 31 * 86400, SKEW = 300;
|
|
28
28
|
export const REPLACE_DAYS = 7, REISSUE = 3600, RETIRED_MAX = 8 * ONE_TIME, USED_MAX = 1024;
|
|
@@ -115,7 +115,7 @@ export class Prekeys {
|
|
|
115
115
|
// Replaces every one-time key listed once they are REPLACE_DAYS old, else tops them up to
|
|
116
116
|
// twenty, rotates the last-resort key if due, and returns a bundle signed by the identity key
|
|
117
117
|
// ("sigelo\n" + JCS(body), SPEC §3). The bundle lists EVERY unused key and replaces the previous
|
|
118
|
-
// one at the contact. me: { current_did, secret
|
|
118
|
+
// one at the contact. me: { current_did, sign } (or secret: kdf.mjs signAs).
|
|
119
119
|
// rng order, for reproducible fixtures: per new one-time key id (16) then keygen seed (32); then
|
|
120
120
|
// the same for a new last-resort key.
|
|
121
121
|
issue(me, pair, now, rng = randomBytes) {
|
|
@@ -142,7 +142,7 @@ export class Prekeys {
|
|
|
142
142
|
const lr = this.lastResort[0];
|
|
143
143
|
const body = { v: MSG_V, typ: 'prekeys', did: me.current_did, pair, iat: now, exp: now + TTL,
|
|
144
144
|
keys: [...this.oneTime].map(([id, k]) => ({ id, pk: b64u(k.publicKey) })), last_resort: { id: lr.id, pk: b64u(lr.publicKey) } };
|
|
145
|
-
return { body, sig:
|
|
145
|
+
return { body, sig: signAs(me, body) };
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
// For the envelope that begins an epoch; nothing is consumed until it has passed every check
|
package/short.mjs
CHANGED
|
@@ -92,6 +92,29 @@ export function makeShort(rng = randomBytes) {
|
|
|
92
92
|
/** The key the relay parks under: hex SHA-256("sigelo-park/0" ‖ the normalised code). */
|
|
93
93
|
export const codeHash = (text) => bytesToHex(sha256(concatBytes(utf8ToBytes(PARK_V), utf8ToBytes(normaliseShort(text)))));
|
|
94
94
|
|
|
95
|
+
// Gift codes (sigelo-gift/0): Pro months for an operator, sold or handed out by the vendor
|
|
96
|
+
// (the issuer makes them offline; relay/gifts.mjs redeems them, POST /gift). The
|
|
97
|
+
// same 8 characters, alphabet and folding as a short code, shown with a prefix of their own,
|
|
98
|
+
// PRO-K7F3-Q9ZP, so a person cannot take one for an invite. Typed in any case, with or without
|
|
99
|
+
// dashes or the PRO prefix. Hashed under a label of their own: a gift's hash is never a parked
|
|
100
|
+
// code's. The relay holds the hash only (code_hash), and a code is in no log or error text.
|
|
101
|
+
export const GIFT_V = 'sigelo-gift/0', GIFT_PREFIX = 'PRO';
|
|
102
|
+
/** The canonical 8 characters of a gift code ("K7F3Q9ZP"), or throws gift_code. */
|
|
103
|
+
export function normaliseGift(text) {
|
|
104
|
+
if (typeof text !== 'string' || text.length > MAX_INPUT) fail('gift_code', 'not a gift code');
|
|
105
|
+
const bare = text.replace(SEPARATORS, '');
|
|
106
|
+
// The prefix, its O folded as a code's is, on anything longer than a code.
|
|
107
|
+
const rest = bare.length > SHORT_LENGTH && bare.slice(0, GIFT_PREFIX.length).toUpperCase().replace('0', 'O') === GIFT_PREFIX ? bare.slice(GIFT_PREFIX.length) : bare;
|
|
108
|
+
try { return normaliseShort(rest); } catch (e) {
|
|
109
|
+
// The short code's reason (the character at fault, the count), without the input it quotes.
|
|
110
|
+
fail('gift_code', `not a gift code (like PRO-K7F3-Q9ZP: PRO, then 8 characters of 0-9 and A-Z without I, L, O, U): ${e.message.replace(/^short_code: (?:"[^"]*" read as a short code \([^)]*\): )?/, '').replaceAll('a short code', 'a gift code').replace('(like K7F3-Q9ZP)', 'after PRO')}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** "K7F3Q9ZP" → "PRO-K7F3-Q9ZP", how a gift code is shown. */
|
|
114
|
+
export const formatGift = (norm) => `${GIFT_PREFIX}-${formatShort(norm)}`;
|
|
115
|
+
/** The key the relay holds a gift under: hex SHA-256("sigelo-gift/0" ‖ the normalised code). */
|
|
116
|
+
export const giftHash = (text) => bytesToHex(sha256(concatBytes(utf8ToBytes(GIFT_V), utf8ToBytes(normaliseGift(text)))));
|
|
117
|
+
|
|
95
118
|
/** The four words of a pairing, from its pair id (32 lowercase hex digits, kdf.pairId). */
|
|
96
119
|
export function fingerprint(pair) {
|
|
97
120
|
const b = hkdf(sha256, unhex(pair, 16, 'pair'), utf8ToBytes(FINGERPRINT_LABEL), new Uint8Array(0), 6);
|
package/test-short.mjs
CHANGED
|
@@ -14,7 +14,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
14
14
|
import { keygen } from 'sigelo';
|
|
15
15
|
import { BIP39_SHA256, WORDS } from './bip39-english.mjs';
|
|
16
16
|
import { makeInvite } from './invite.mjs';
|
|
17
|
-
import { ALPHABET, SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, isShort, makeShort, normaliseShort } from './short.mjs';
|
|
17
|
+
import { ALPHABET, GIFT_V, SHORT_TTL, codeHash, codeKind, fingerprint, formatGift, formatShort, giftHash, isShort, makeShort, normaliseGift, normaliseShort } from './short.mjs';
|
|
18
18
|
|
|
19
19
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
20
20
|
let count = 0;
|
|
@@ -88,6 +88,26 @@ const report = () => {
|
|
|
88
88
|
ok(parked.startsWith('code_length: the long code the relay holds for this short code does not parse'), `a parked code that does not parse: blamed on what the relay holds (${parked})`);
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
// ================================================================ gift codes (sigelo-gift/0)
|
|
92
|
+
// A short code's 8 characters, alphabet and folding, shown PRO-K7F3-Q9ZP; hashed under a label of
|
|
93
|
+
// its own, never the park label.
|
|
94
|
+
{
|
|
95
|
+
ok(GIFT_V === 'sigelo-gift/0' && formatGift('K7F3Q9ZP') === 'PRO-K7F3-Q9ZP', 'a gift code is shown PRO-K7F3-Q9ZP; its label is sigelo-gift/0');
|
|
96
|
+
const forms = ['PRO-K7F3-Q9ZP', 'pro-k7f3-q9zp', 'PROK7F3Q9ZP', 'pro k7f3 q9zp', 'PR0-K7F3-Q9ZP', 'K7F3-Q9ZP', 'k7f3q9zp', 'PRO\u2013K7F3\u2013Q9ZP', 'PRO-K7F3-Q9Z0'.replace('0', 'P')];
|
|
97
|
+
ok(forms.every((f) => normaliseGift(f) === 'K7F3Q9ZP'), `normaliseGift: any case, with or without dashes, spaces or the PRO prefix (its O typed 0 too) → K7F3Q9ZP`);
|
|
98
|
+
ok(normaliseGift('PRO-K7F3-Q9Z0') === 'K7F3Q9Z0' && normaliseGift('PRO-1L0I-OOOO') === '11010000', 'normaliseGift folds I and L to 1, O to 0, as a short code does');
|
|
99
|
+
const want = createHash('sha256').update('sigelo-gift/0K7F3Q9ZP').digest('hex');
|
|
100
|
+
ok(giftHash('PRO-K7F3-Q9ZP') === want && giftHash('k7f3 q9zp') === want && giftHash('PRO-K7F3-Q9ZP') !== codeHash('K7F3-Q9ZP'),
|
|
101
|
+
`giftHash = hex SHA-256("sigelo-gift/0" ‖ the 8 characters) (${want.slice(0, 16)}…), never the park hash of the same characters`);
|
|
102
|
+
for (const [t, why] of [['PRO-AB12-U9ZP', 'character 5 "U" is not in the alphabet'], ['PRO-AB12-CD3', '7 characters, a gift code has 8 after PRO: 1 missing'], ['PRO-AB12-CD34X', '1 too many'], ['sgl1abc', 'not a gift code'], [undefined, 'not a gift code']]) {
|
|
103
|
+
const m = messageOf(() => normaliseGift(t));
|
|
104
|
+
ok(checkOf(() => normaliseGift(t)) === 'gift_code' && m.includes(why) && (t === undefined || !m.includes(t)), `normaliseGift ${JSON.stringify(t)}: gift_code, ${why}, the input not quoted (${m})`);
|
|
105
|
+
}
|
|
106
|
+
// makeShort makes gift codes too (made offline by the issuer): any of its codes reads back.
|
|
107
|
+
const g = makeShort();
|
|
108
|
+
ok(normaliseGift(formatGift(g)) === g, 'a code from makeShort, shown as a gift code, reads back');
|
|
109
|
+
}
|
|
110
|
+
|
|
91
111
|
const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', 'relay');
|
|
92
112
|
if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
|
|
93
113
|
report();
|
|
@@ -237,6 +257,17 @@ try {
|
|
|
237
257
|
ok(gb.events.filter((e) => e.type === 'pairing_failed' && e.code === 'code_expired').length === 1 && Date.now() - t2 < 30000,
|
|
238
258
|
`inbox --wait 60 ends when the answer expires, and says so (${JSON.stringify(gb.events)}, ${Date.now() - t2} ms)`);
|
|
239
259
|
await cg.stop();
|
|
260
|
+
// A gift code (relay/gifts.mjs), redeemed by carol as the operator: the relay gets its hash only.
|
|
261
|
+
const gift = makeShort(), shown = formatGift(gift);
|
|
262
|
+
relay.db.raw.prepare('INSERT INTO gift_campaigns (campaign, issued) VALUES (?, 1)').run('test');
|
|
263
|
+
relay.db.raw.prepare('INSERT INTO gifts (code_hash, campaign, months, expires) VALUES (?, ?, ?, ?)').run(giftHash(shown), 'test', 1, Math.floor(now / 86400) * 86400 + 30 * 86400);
|
|
264
|
+
const gr = await cc.redeemGift(shown.toLowerCase());
|
|
265
|
+
ok(gr.months === 1 && gr.exp > now + 27 * 86400 && gr.exp % 86400 === 0, `redeemGift: a fresh identity (proof of work in the same login) redeems 1 month, Pro to the start of a UTC day (${JSON.stringify(gr)})`);
|
|
266
|
+
const g2 = await failure(() => cc.redeemGift(shown));
|
|
267
|
+
ok(g2.check === 'gift' && !g2.message.includes(gift) && !g2.message.includes(giftHash(shown)), `redeemGift twice: refused "gift", the code not quoted (${g2.message})`);
|
|
268
|
+
const g3 = await failure(() => cc.redeemGift('PRO-K7F3-U9ZP'));
|
|
269
|
+
ok(g3.check === 'gift_code', 'redeemGift of a malformed code: gift_code, refused before any login');
|
|
270
|
+
ok(!lines.some((l) => l.includes(gift) || l.includes(giftHash(shown))), 'the relay log holds neither the gift code nor its hash');
|
|
240
271
|
// The database holds no short code and no long code (memory only).
|
|
241
272
|
const dump = readFileSync(join(dir, 'relay.db')).toString('latin1') + (existsSync(join(dir, 'relay.db-wal')) ? readFileSync(join(dir, 'relay.db-wal')).toString('latin1') : '');
|
|
242
273
|
ok(![inv.short, normaliseShort(inv.short), codeHash(inv.short), inv.code, late.code].some((s) => dump.includes(s)), 'the relay\'s database files hold no code, no hash, no parked invite');
|
package/test-ws.mjs
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// The carrier (carrier.mjs) over MQTT over WebSocket, against a loopback relay (relay/server.mjs)
|
|
3
|
+
// whose only listener is its HTTP port: two agents pair, write and read with 8883 unreachable,
|
|
4
|
+
// with transport "wss" and with "auto" (the default), which falls back once, after the probe when
|
|
5
|
+
// 8883 is silent, and keeps to WebSocket for the rest of the process. Then, in a child process with only an HTTP CONNECT proxy to reach the relay
|
|
6
|
+
// (HTTPS_PROXY; the relay's name resolves nowhere, its certificate trusted by NODE_EXTRA_CA_CERTS),
|
|
7
|
+
// the same through a stand-in nginx with TLS, whose relay.json names the WebSocket endpoint. Also:
|
|
8
|
+
// endpointOf and proxyFor (NO_PROXY), SIGELO_RELAY_TRANSPORT, and a message refused because the
|
|
9
|
+
// reader's queue is full, told as the reader's side (quota_storage, side "reader").
|
|
10
|
+
// node contact/test-ws.mjs → ALL PASS (n)
|
|
11
|
+
// The relay is its own AGPL package: SIGELO_RELAY_DIR, else ../relay; without it, SKIP after the
|
|
12
|
+
// part that needs none.
|
|
13
|
+
import { spawn } from 'node:child_process';
|
|
14
|
+
import { createHash, generateKeyPairSync, randomBytes, sign as cryptoSign } from 'node:crypto';
|
|
15
|
+
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { createServer, request as httpRequest } from 'node:http';
|
|
17
|
+
import { createServer as createHttpsServer } from 'node:https';
|
|
18
|
+
import { connect as netConnect, createServer as createNetServer } from 'node:net';
|
|
19
|
+
import { tmpdir } from 'node:os';
|
|
20
|
+
import { dirname, join } from 'node:path';
|
|
21
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
22
|
+
import { keygen } from 'sigelo';
|
|
23
|
+
import { Carrier, PROBE_MS, endpointOf, optionsFromEnv, pathsFor, proxyFor } from './carrier.mjs';
|
|
24
|
+
|
|
25
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
26
|
+
const HOST = 'relay.test', CREATED = '2026-10-01T00:00:00Z';
|
|
27
|
+
const seed = (l) => new Uint8Array(createHash('sha256').update(`sigelo-ws-test/0 ${l}`).digest());
|
|
28
|
+
function agent(label) {
|
|
29
|
+
const recovery = keygen({ seed: seed(`${label} recovery`), recovery: 'sha256:' + '0'.repeat(64), created: CREATED, nonce: seed(`${label} rn`).slice(0, 16) }).key;
|
|
30
|
+
const k = keygen({ seed: seed(label), recovery, created: CREATED, nonce: seed(`${label} nonce`).slice(0, 16) });
|
|
31
|
+
return { label, original: k.did, did: k.did, secret: k.secret, bundle: { v: 'sigelo/0', typ: 'bundle', genesis: k.genesis, rotations: [], bindings: [], attestations: [], issuers: [] } };
|
|
32
|
+
}
|
|
33
|
+
const make = (dir, a, extra = {}) => {
|
|
34
|
+
const events = [];
|
|
35
|
+
const c = new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...pathsFor(join(dir, `${a.label}.local.json`)), relay: HOST,
|
|
36
|
+
onEvent: (e) => events.push(e), keep: true, backoff: [100, 400], retentionDays: 7, ...extra });
|
|
37
|
+
c.events = events;
|
|
38
|
+
return c;
|
|
39
|
+
};
|
|
40
|
+
// Pair x and y by code, each reading in turn, then one message each way. → what each read.
|
|
41
|
+
async function pairAndTalk(x, y, tag) {
|
|
42
|
+
const inv = await x.invite({ name: 'y' });
|
|
43
|
+
const acc = await y.accept(inv.code, { name: 'x', wait: 0.3 });
|
|
44
|
+
await x.inbox(); await y.inbox(); await x.inbox();
|
|
45
|
+
const s1 = await x.send('y', `hello from x ${tag}`), s2 = await y.send('x', `hello from y ${tag}`);
|
|
46
|
+
const ry = await y.inbox(), rx = await x.inbox();
|
|
47
|
+
return { accepted: acc.status, sent: [s1.status, s2.status], gotY: ry.messages.map((m) => m.content), gotX: rx.messages.map((m) => m.content) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ================================================================ the child: behind a proxy only
|
|
51
|
+
if (process.argv[2] === '--child') {
|
|
52
|
+
const [, , , dir] = process.argv;
|
|
53
|
+
const out = {};
|
|
54
|
+
try {
|
|
55
|
+
const x = make(dir, agent('px'), optionsFromEnv()), y = make(dir, agent('py'), optionsFromEnv());
|
|
56
|
+
Object.assign(out, await pairAndTalk(x, y, 'via proxy'));
|
|
57
|
+
out.transport = [x, y].map((c) => c.events.find((e) => e.type === 'transport')?.transport ?? null);
|
|
58
|
+
out.fellBack = x.events.find((e) => e.type === 'transport')?.detail ?? null;
|
|
59
|
+
} catch (e) { out.error = `${e.check ?? e.name}: ${e.message}`; }
|
|
60
|
+
console.log(JSON.stringify(out));
|
|
61
|
+
process.exit(0);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let count = 0;
|
|
65
|
+
const fails = [];
|
|
66
|
+
const ok = (cond, what) => { count++; if (!cond) fails.push(what); };
|
|
67
|
+
const report = (skip = '') => {
|
|
68
|
+
for (const f of fails) console.log('FAIL ' + f);
|
|
69
|
+
if (fails.length) { console.log(`${fails.length} FAILED, ${count - fails.length} passed`); process.exit(1); }
|
|
70
|
+
console.log(`ALL PASS (${count})${skip}`);
|
|
71
|
+
process.exit(0);
|
|
72
|
+
};
|
|
73
|
+
setTimeout(() => { console.log(`FAIL the run did not finish in 240 s (${count} checks so far)`); process.exit(1); }, 240000).unref();
|
|
74
|
+
const checkOf = (f) => { try { f(); return 'accepted'; } catch (e) { return e.check ?? e.message; } };
|
|
75
|
+
|
|
76
|
+
// ================================================================ endpoints, proxies, the setting
|
|
77
|
+
{
|
|
78
|
+
const d = endpointOf('relay.sigelo.ai');
|
|
79
|
+
ok(d.mqtt === 'mqtts://relay.sigelo.ai:8883' && d.ws === 'wss://relay.sigelo.ai/mqtt' && d.http === 'https://relay.sigelo.ai', `a relay string: mqtts on 8883, wss at /mqtt on 443 (${JSON.stringify(d)})`);
|
|
80
|
+
ok(endpointOf('r', { r: { mqtt: 'wss://r.example/mqtt', http: 'https://r.example' } }).mqtt === 'wss://r.example/mqtt', 'endpoints: mqtt may be wss://');
|
|
81
|
+
ok(endpointOf('r', { r: { mqtt: 'mqtt://127.0.0.1:1', http: 'http://127.0.0.1:2' } }).ws === 'ws://127.0.0.1:2/mqtt', 'endpoints: ws defaults to the http origin at /mqtt (ws:// for a loopback http://)');
|
|
82
|
+
ok(checkOf(() => endpointOf('r', { r: { mqtt: 'ws://r.example/mqtt', http: 'https://r.example' } })) === 'relay'
|
|
83
|
+
&& checkOf(() => endpointOf('r', { r: { mqtt: 'mqtts://r.example', http: 'https://r.example', ws: 'ws://r.example/mqtt' } })) === 'relay',
|
|
84
|
+
'endpoints: ws:// only to a loopback address, as mqtt:// and http://');
|
|
85
|
+
const env = { HTTPS_PROXY: 'http://user:pw@proxy.example:3128', NO_PROXY: 'internal.example, .corp.example,10.1.2.3,*.lab.example,api.example:8443' };
|
|
86
|
+
const via = (u, e = env) => proxyFor(u, e)?.host ?? null;
|
|
87
|
+
ok(via('https://relay.sigelo.ai/challenge') === 'proxy.example:3128' && via('wss://relay.sigelo.ai/mqtt') === 'proxy.example:3128', 'proxyFor: HTTPS_PROXY carries https:// and wss://');
|
|
88
|
+
ok(via('http://127.0.0.1:1/') === null && via('ws://127.0.0.1:1/mqtt') === null, 'proxyFor: never plain http:// or ws://');
|
|
89
|
+
ok(['https://internal.example', 'https://a.internal.example', 'https://x.corp.example', 'https://corp.example', 'https://10.1.2.3', 'https://b.lab.example', 'https://api.example:8443'].every((u) => via(u) === null),
|
|
90
|
+
'proxyFor: NO_PROXY by name and its subdomains, a leading "." or "*.", an address, a name with its port');
|
|
91
|
+
ok(via('https://api.example') === 'proxy.example:3128' && via('https://notinternal.example') === 'proxy.example:3128', 'proxyFor: a port that differs, or a name that only ends alike: proxied');
|
|
92
|
+
ok(via('https://x', { https_proxy: 'proxy:8080' }) === 'proxy:8080' && via('https://x', { HTTPS_PROXY: 'http://p:1', NO_PROXY: '*' }) === null && via('https://x', {}) === null,
|
|
93
|
+
'proxyFor: https_proxy too, a bare host:port as http://; NO_PROXY=* and no proxy at all: none');
|
|
94
|
+
ok(checkOf(() => proxyFor('https://x', { HTTPS_PROXY: 'socks5://p:1080' })) === 'connect', 'proxyFor: a proxy that is not http:// is refused by name');
|
|
95
|
+
ok(optionsFromEnv({}).transport === undefined && optionsFromEnv({ SIGELO_RELAY_TRANSPORT: 'auto' }).transport === 'auto' && checkOf(() => optionsFromEnv({ SIGELO_RELAY_TRANSPORT: 'tcp' })) === 'relay',
|
|
96
|
+
'SIGELO_RELAY_TRANSPORT: unset leaves the default; mqtts, wss or auto; anything else refused');
|
|
97
|
+
ok(checkOf(() => new Carrier({ identity: () => ({}), store: 'a', state: 'b', transport: 'ws' })).includes('transport'), 'the constructor refuses another transport');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', 'relay');
|
|
101
|
+
if (!existsSync(join(RELAY_DIR, 'server.mjs'))) report(': the part without a relay; SKIP the rest, no relay checkout beside contact/ (set SIGELO_RELAY_DIR)');
|
|
102
|
+
const { startRelay } = await import(pathToFileURL(join(RELAY_DIR, 'server.mjs')).href);
|
|
103
|
+
const { relayPolicy, TIERS } = await import(pathToFileURL(join(RELAY_DIR, 'allowance.mjs')).href);
|
|
104
|
+
|
|
105
|
+
const dir = mkdtempSync(join(tmpdir(), 'sigelo-ws-'));
|
|
106
|
+
const listen = (server) => new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port)));
|
|
107
|
+
// An MQTT port that answers nothing: each connection closed at once, counted.
|
|
108
|
+
const dead = { n: 0 };
|
|
109
|
+
const deadServer = createNetServer((s) => { dead.n++; s.destroy(); });
|
|
110
|
+
const deadPort = await listen(deadServer);
|
|
111
|
+
const relayLines = [];
|
|
112
|
+
const relay = await startRelay({ host: HOST, db: join(dir, 'relay.db'), httpPort: 0, loginRate: 100000, verifyBudget: 1e9, log: (l) => relayLines.push(l) });
|
|
113
|
+
const httpBase = `http://127.0.0.1:${relay.ports.http}`;
|
|
114
|
+
try {
|
|
115
|
+
// ================================================================ wss, 8883 unreachable
|
|
116
|
+
{
|
|
117
|
+
// No MQTT listener at all: mqtt names a port that closes every connection.
|
|
118
|
+
const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${deadPort}`, http: httpBase } };
|
|
119
|
+
const x = make(dir, agent('wx'), { endpoints, transport: 'wss' }), y = make(dir, agent('wy'), { endpoints, transport: 'wss' });
|
|
120
|
+
const r = await pairAndTalk(x, y, 'wss');
|
|
121
|
+
ok(r.accepted === 'waiting' && r.sent.join() === 'sent,sent' && r.gotY.join() === 'hello from x wss' && r.gotX.join() === 'hello from y wss',
|
|
122
|
+
`transport wss: login, claim, send and receive over WebSocket only (${JSON.stringify(r)})`);
|
|
123
|
+
ok(dead.n === 0, `and 8883 was never dialled (${dead.n})`);
|
|
124
|
+
}
|
|
125
|
+
// ================================================================ auto: 8883 first, then WebSocket, kept
|
|
126
|
+
{
|
|
127
|
+
const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${deadPort}`, http: httpBase } };
|
|
128
|
+
const x = make(dir, agent('ax'), { endpoints, transport: 'auto' }), y = make(dir, agent('ay'), { endpoints, transport: 'auto' });
|
|
129
|
+
const t0 = Date.now(), inv = await x.invite({ name: 'y' });
|
|
130
|
+
const fell = x.events.find((e) => e.type === 'transport');
|
|
131
|
+
ok(dead.n === 1 && fell?.transport === 'wss' && /ws:\/\/127\.0\.0\.1:\d+\/mqtt/.test(fell.detail) && Date.now() - t0 < PROBE_MS + 5000,
|
|
132
|
+
`transport auto: the MQTT port tried once, then WebSocket, said by a "transport" event (${dead.n} dial; ${fell?.detail})`);
|
|
133
|
+
await y.accept(inv.code, { name: 'x', wait: 0.3 });
|
|
134
|
+
await x.inbox(); await y.inbox(); await x.inbox();
|
|
135
|
+
const s = await x.send('y', 'auto hello'), got = await y.inbox();
|
|
136
|
+
ok(s.status === 'sent' && got.messages.map((m) => m.content).join() === 'auto hello', `transport auto: paired, sent and read over WebSocket (${s.status})`);
|
|
137
|
+
ok(dead.n === 1, `every later connection, of both agents, went straight to WebSocket: the fallback is kept for the process (${dead.n} dial in all)`);
|
|
138
|
+
// Transport mqtts: the MQTT port only, no fallback.
|
|
139
|
+
const m = make(dir, agent('mx'), { endpoints, transport: 'mqtts' });
|
|
140
|
+
let why = null;
|
|
141
|
+
try { await m.invite(); } catch (e) { why = e.check; }
|
|
142
|
+
ok(why === 'connect' && dead.n === 2 && !m.events.some((e) => e.type === 'transport'), `transport mqtts: the MQTT port only, no fallback (${why})`);
|
|
143
|
+
}
|
|
144
|
+
// ================================================================ the default (auto), 8883 dropped
|
|
145
|
+
{
|
|
146
|
+
// An MQTT port that takes the connection and never answers: a firewall that drops, not refuses.
|
|
147
|
+
const held = [];
|
|
148
|
+
const silent = createNetServer((s) => { held.push(s); s.on('error', () => {}); });
|
|
149
|
+
const silentPort = await listen(silent);
|
|
150
|
+
try {
|
|
151
|
+
const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${silentPort}`, http: httpBase } };
|
|
152
|
+
const x = make(dir, agent('dx'), { endpoints });
|
|
153
|
+
ok(x.transport === 'auto', `no transport option and no SIGELO_RELAY_TRANSPORT: the carrier's transport is auto (${x.transport})`);
|
|
154
|
+
const t0 = Date.now(), inv = await x.invite({ name: 'y' }), ms = Date.now() - t0;
|
|
155
|
+
const fell = x.events.find((e) => e.type === 'transport');
|
|
156
|
+
ok(typeof inv.code === 'string' && held.length === 1 && fell?.transport === 'wss' && ms >= PROBE_MS - 100 && ms < PROBE_MS + 5000,
|
|
157
|
+
`the default, 8883 silent: connected over WebSocket after the ${PROBE_MS / 1000} s probe (${ms} ms, ${held.length} dial; ${fell?.detail})`);
|
|
158
|
+
} finally { for (const s of held) s.destroy(); silent.close(); }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ================================================================ only an HTTP CONNECT proxy
|
|
162
|
+
{
|
|
163
|
+
// A self-signed certificate for relay.test (relay/test/fixtures.mjs builds one per run).
|
|
164
|
+
const { selfSigned } = await import(pathToFileURL(join(RELAY_DIR, 'test', 'fixtures.mjs')).href);
|
|
165
|
+
const cert = selfSigned(HOST), caFile = join(dir, 'ca.pem');
|
|
166
|
+
writeFileSync(caFile, cert.cert);
|
|
167
|
+
// The stand-in nginx, TLS on 443's behalf: relay.json naming the WebSocket endpoint at another
|
|
168
|
+
// path (/mqtt-alt), which it passes to the relay's /mqtt with X-Real-IP; /mqtt itself it does not
|
|
169
|
+
// serve, so a client that ignored relay.json fails. Every other call passed on as it came.
|
|
170
|
+
const front = createHttpsServer({ cert: cert.cert, key: cert.key }, (req, res) => {
|
|
171
|
+
if (req.url === '/relay.json') { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ endpoints: { mqtt: `mqtts://${HOST}:8883`, mqtt_ws: `wss://${HOST}/mqtt-alt` } })); return; }
|
|
172
|
+
const up = httpRequest(`${httpBase}${req.url}`, { method: req.method, headers: { ...req.headers, 'x-real-ip': '198.51.100.7' } }, (r) => { res.writeHead(r.statusCode, r.headers); r.pipe(res); });
|
|
173
|
+
up.on('error', () => res.destroy());
|
|
174
|
+
req.pipe(up);
|
|
175
|
+
});
|
|
176
|
+
front.on('upgrade', (req, sock, head) => {
|
|
177
|
+
if (req.url !== '/mqtt-alt') return sock.end('HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n');
|
|
178
|
+
const up = netConnect(relay.ports.http, '127.0.0.1', () => {
|
|
179
|
+
const h = Object.entries({ ...req.headers, 'x-real-ip': '198.51.100.7' }).map(([k, v]) => `${k}: ${v}`).join('\r\n');
|
|
180
|
+
up.write(`GET /mqtt HTTP/1.1\r\n${h}\r\n\r\n`); up.write(head); up.pipe(sock); sock.pipe(up);
|
|
181
|
+
});
|
|
182
|
+
for (const s of [up, sock]) { s.on('error', () => { up.destroy(); sock.destroy(); }); s.on('close', () => { up.destroy(); sock.destroy(); }); }
|
|
183
|
+
});
|
|
184
|
+
const frontPort = await listen(front);
|
|
185
|
+
// The proxy: CONNECT relay.test:443 only, to the front; anything else 403. Counted.
|
|
186
|
+
const asked = [];
|
|
187
|
+
const proxy = createServer((req, res) => { res.writeHead(405); res.end(); });
|
|
188
|
+
proxy.on('connect', (req, sock, head) => {
|
|
189
|
+
asked.push(req.url);
|
|
190
|
+
if (req.url !== `${HOST}:443`) return sock.end('HTTP/1.1 403 Forbidden\r\n\r\n');
|
|
191
|
+
const up = netConnect(frontPort, '127.0.0.1', () => { sock.write('HTTP/1.1 200 Connection Established\r\n\r\n'); up.write(head); up.pipe(sock); sock.pipe(up); });
|
|
192
|
+
for (const s of [up, sock]) s.on('error', () => { up.destroy(); sock.destroy(); });
|
|
193
|
+
});
|
|
194
|
+
const proxyPort = await listen(proxy);
|
|
195
|
+
const env = { PATH: process.env.PATH, HOME: process.env.HOME, NODE_EXTRA_CA_CERTS: caFile, HTTPS_PROXY: `http://127.0.0.1:${proxyPort}`, SIGELO_RELAY_TRANSPORT: 'auto' };
|
|
196
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--child', dir], { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
197
|
+
let out = '', err = '';
|
|
198
|
+
child.stdout.on('data', (b) => { out += b; }); child.stderr.on('data', (b) => { err += b; });
|
|
199
|
+
await new Promise((resolve) => child.once('exit', resolve));
|
|
200
|
+
let r = {};
|
|
201
|
+
try { r = JSON.parse(out.trim().split('\n').at(-1)); } catch { r = { error: `no result: ${out}${err}`.slice(0, 600) }; }
|
|
202
|
+
ok(!r.error && r.accepted === 'waiting' && r.sent?.join() === 'sent,sent' && r.gotY?.join() === 'hello from x via proxy' && r.gotX?.join() === 'hello from y via proxy',
|
|
203
|
+
`behind an HTTP CONNECT proxy only (8883 unreachable, the name resolving nowhere): login, claim, send and receive (${JSON.stringify(r)})`);
|
|
204
|
+
ok(r.transport?.join() === 'wss,' && /wss:\/\/relay\.test\/mqtt-alt/.test(r.fellBack ?? ''), `auto fell back once, to the WebSocket endpoint relay.json names; the second agent of the process went there directly (${r.transport}; ${r.fellBack})`);
|
|
205
|
+
ok(asked.length > 0 && asked.every((u) => u === `${HOST}:443`), `every HTTPS call and the WebSocket went through the proxy as CONNECT ${HOST}:443 (${asked.length} tunnels)`);
|
|
206
|
+
ok(relayLines.filter((l) => l === 'login 198.51.100.0/24').length >= 2, 'the relay counted those WebSocket logins under the network the front sent as X-Real-IP, not its own loopback');
|
|
207
|
+
for (const s of [front, proxy]) { s.closeAllConnections?.(); s.close(); }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ================================================================ the reader's quota, told as such
|
|
211
|
+
{
|
|
212
|
+
// A relay whose free tier holds 200,000 bytes per reader: y, offline, fills; x is told the
|
|
213
|
+
// refusal is y's side (quota_storage, side "reader"), not its relay or its own allowance.
|
|
214
|
+
const tiny = { ...TIERS.free, storage: 200000, maxMessage: 64 * 1024, retentionDays: 7 };
|
|
215
|
+
const q = await startRelay({ host: HOST, db: join(dir, 'quota.db'), httpPort: 0, tcpPort: 0, loginRate: 100000, verifyBudget: 1e9, log: () => {},
|
|
216
|
+
policy: (ctx) => relayPolicy(ctx, { pow: { bits: 4, loadBits: 8, loadPerHour: 1000 }, freeQueue: 64 * 1024 * 1024, tiers: { free: tiny, pro: TIERS.pro } }) });
|
|
217
|
+
const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${q.ports.tcp}`, http: `http://127.0.0.1:${q.ports.http}` } };
|
|
218
|
+
const x = make(dir, agent('qx'), { endpoints }), y = make(dir, agent('qy'), { endpoints });
|
|
219
|
+
const r = await pairAndTalk(x, y, 'quota');
|
|
220
|
+
ok(r.gotY.length === 1, 'two agents paired on a relay with a 200,000-byte free reader');
|
|
221
|
+
let s = null, thrown = null;
|
|
222
|
+
for (let i = 0; i < 8 && !thrown; i++) { try { await x.send('y', 'z'.repeat(40000)); } catch (e) { thrown = e; } }
|
|
223
|
+
ok(thrown?.check === 'quota_storage' && thrown.side === 'reader' && /refused \(y's side is over its storage quota/.test(thrown.message) && /nothing is wrong with your relay/.test(thrown.message) && /reader over quota/.test(thrown.message),
|
|
224
|
+
`y's queue full: send refuses quota_storage, side "reader", told as y's side, the relay's words quoted (${thrown?.message})`);
|
|
225
|
+
[s] = await x.sendAll('y', ['z'.repeat(40000)]);
|
|
226
|
+
ok(s?.status === 'refused' && s.code === 'quota_storage' && s.side === 'reader' && /^y's side/.test(s.detail), `sendAll: the same, as a result (${JSON.stringify(s).slice(0, 200)})`);
|
|
227
|
+
ok(x.events.some((e) => e.type === 'refused' && e.code === 'quota_storage' && e.side === 'reader'), 'the refused event carries side "reader" too');
|
|
228
|
+
await q.close();
|
|
229
|
+
}
|
|
230
|
+
} catch (e) {
|
|
231
|
+
fails.push(`exception: ${e.stack}`);
|
|
232
|
+
} finally {
|
|
233
|
+
await relay.close();
|
|
234
|
+
deadServer.close();
|
|
235
|
+
rmSync(dir, { recursive: true, force: true });
|
|
236
|
+
}
|
|
237
|
+
report();
|