sigelo-contact 0.1.5 → 0.1.6
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/carrier.mjs +123 -33
- package/invite.mjs +15 -8
- package/kdf.mjs +10 -2
- package/package.json +2 -2
- package/short.mjs +30 -5
- package/store.mjs +18 -1
- package/test-carrier.mjs +4 -1
- package/test-short.mjs +92 -3
package/carrier.mjs
CHANGED
|
@@ -8,11 +8,14 @@
|
|
|
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
10
|
// await c.accept(code, { name, wait }) → { status: 'connected' | 'waiting' | 'pending', … } a long code or a short one
|
|
11
|
-
//
|
|
11
|
+
// (refused after a short code was fetched: .long, keepLong)
|
|
12
|
+
// c.contacts() → { contacts, invites, answers, failed } each contact with its four words (fingerprint);
|
|
13
|
+
// failed: pairing_failed events (code_expired: an answer that outlived its code) until inbox
|
|
12
14
|
// await c.send(to, content, { label }) → { status: 'sent' | 'queued', … }, or throws the relay's code
|
|
13
15
|
// await c.sendAll(to, contents, { label }) → one result each ('refused' with its code), one login
|
|
14
16
|
// await c.inbox({ wait }) → { messages, events, dropped, offline? }: all are taken (messages: those kept)
|
|
15
17
|
// await c.forget(did) → { name, did, revoked: true, released, offline? }
|
|
18
|
+
// c.lastError the error behind the last offline of inbox or forget (SIGELO_DEBUG)
|
|
16
19
|
// await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
|
|
17
20
|
//
|
|
18
21
|
// identity() → { secret, bundle }: the agent's current secret key and SPEC §8 bundle, read again at
|
|
@@ -151,7 +154,7 @@ import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, inviteKeys,
|
|
|
151
154
|
import { MsgError, checkNow, fail, hex, isoWeek, pairId, topic } from './kdf.mjs';
|
|
152
155
|
import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
|
|
153
156
|
import { Contacts } from './store.mjs';
|
|
154
|
-
import { SHORT_TTL, codeHash, fingerprint, formatShort,
|
|
157
|
+
import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, makeShort, normaliseShort } from './short.mjs';
|
|
155
158
|
|
|
156
159
|
export const V = 'sigelo-carrier/0';
|
|
157
160
|
export const DEFAULT_RELAY = 'relay.sigelo.ai', MQTT_PORT = 8883, NOTICE = '$sigelo/notice';
|
|
@@ -319,7 +322,7 @@ export function optionsFromEnv(env = process.env) {
|
|
|
319
322
|
const o = {};
|
|
320
323
|
if (env.SIGELO_RELAY) o.relay = env.SIGELO_RELAY;
|
|
321
324
|
if (env.SIGELO_RELAY_ENDPOINTS) {
|
|
322
|
-
try { o.endpoints = JSON.parse(env.SIGELO_RELAY_ENDPOINTS); } catch { fail('relay', 'SIGELO_RELAY_ENDPOINTS is not JSON'); }
|
|
325
|
+
try { o.endpoints = JSON.parse(env.SIGELO_RELAY_ENDPOINTS); } catch { fail('relay', 'SIGELO_RELAY_ENDPOINTS is not JSON: want {"<relay>": {"mqtt": "mqtts://…", "http": "https://…"}}'); }
|
|
323
326
|
}
|
|
324
327
|
if (env.SIGELO_RELAY_RETENTION_DAYS) {
|
|
325
328
|
const n = Number(env.SIGELO_RELAY_RETENTION_DAYS);
|
|
@@ -528,28 +531,70 @@ export async function solvePow(host, original, nonce, bits, deadline = Infinity)
|
|
|
528
531
|
// past publicRelay's check on the code's host. A relay never needs one: `connect`.
|
|
529
532
|
async function http(url, init = {}) {
|
|
530
533
|
let res;
|
|
531
|
-
|
|
534
|
+
const at = where(url), http = { url, method: init.method ?? 'GET' };
|
|
535
|
+
try { res = await fetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(HTTP_MS) }); } catch (e) {
|
|
536
|
+
const why = e.name === 'TimeoutError' ? `no answer within ${HTTP_MS / 1000} s` : e.cause?.code ?? e.cause?.message ?? e.message;
|
|
537
|
+
fail('connect', `cannot reach the relay at ${at} (${why}): check the network and SIGELO_RELAY / SIGELO_RELAY_ENDPOINTS, then try again`, { cause: e, http });
|
|
538
|
+
}
|
|
539
|
+
http.status = res.status;
|
|
532
540
|
if ((res.status >= 300 && res.status < 400) || res.type === 'opaqueredirect') {
|
|
533
541
|
try { await res.body?.cancel(); } catch {}
|
|
534
|
-
fail('connect', `${
|
|
542
|
+
fail('connect', `${at}: answered ${res.status}, a redirect, which this client does not follow`, { http });
|
|
535
543
|
}
|
|
536
|
-
if (Number(res.headers.get('content-length') ?? 0) > HTTP_MAX) fail('connect', `${
|
|
544
|
+
if (Number(res.headers.get('content-length') ?? 0) > HTTP_MAX) fail('connect', `${at}: answer over ${HTTP_MAX} bytes`, { http });
|
|
537
545
|
const chunks = [];
|
|
538
546
|
let n = 0;
|
|
539
547
|
try {
|
|
540
548
|
// Leaving the loop by a throw cancels the stream: nothing more is read.
|
|
541
549
|
for await (const chunk of res.body ?? []) {
|
|
542
550
|
n += chunk.length;
|
|
543
|
-
if (n > HTTP_MAX) fail('connect', `${
|
|
551
|
+
if (n > HTTP_MAX) fail('connect', `${at}: answer over ${HTTP_MAX} bytes`, { http });
|
|
544
552
|
chunks.push(chunk);
|
|
545
553
|
}
|
|
546
554
|
} catch (e) {
|
|
547
555
|
if (e instanceof MsgError) throw e;
|
|
548
|
-
fail('connect', `${
|
|
556
|
+
fail('connect', `${at}: the answer broke off (${e.cause?.code ?? e.message}): try again`, { cause: e, http });
|
|
549
557
|
}
|
|
550
558
|
let body = null;
|
|
551
|
-
|
|
552
|
-
|
|
559
|
+
const raw = concatBytes(...chunks);
|
|
560
|
+
try { body = parseBytes(raw); } catch {}
|
|
561
|
+
// Seconds the relay asks to wait (Retry-After), when it says.
|
|
562
|
+
const after = Number(res.headers.get('retry-after'));
|
|
563
|
+
// What a refusal carries for SIGELO_DEBUG: the status and the start of the body as received.
|
|
564
|
+
http.body = new TextDecoder().decode(raw.subarray(0, 512));
|
|
565
|
+
return { status: res.status, body, retryAfter: Number.isSafeInteger(after) && after > 0 ? after : null, http };
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// A URL as a refusal shows it: no query (it carries the DID), no code hash.
|
|
569
|
+
function where(url) {
|
|
570
|
+
try { const u = new URL(url); return u.origin + u.pathname.replace(/\/[0-9a-f]{64}$/, '/<code hash>'); } catch { return String(url); }
|
|
571
|
+
}
|
|
572
|
+
// A refusal of a relay's HTTP answer r, with the answer kept for SIGELO_DEBUG.
|
|
573
|
+
const refuse = (check, why, r) => fail(check, why, { http: r.http });
|
|
574
|
+
// When to try again after a 429: the relay's Retry-After, else the window its brake counts in.
|
|
575
|
+
const retryIn = (r, window) => (r.retryAfter ? `wait ${r.retryAfter} s` : `wait ${window}`);
|
|
576
|
+
// A status no answer about this agent: the relay is down, restarting, or behind a proxy that is.
|
|
577
|
+
const statusWhy = (r, what) => `the relay answered ${r.status} to ${what}${r.status >= 500 ? ': it is down or restarting; try again in a few minutes' : ': try again later; SIGELO_DEBUG=1 shows the answer'}`;
|
|
578
|
+
/** A long code (or one fetched by a short one: parked) read with parseInvite; a malformed one
|
|
579
|
+
* is refused saying how the input was read, so a mistyped short code never reads "does not
|
|
580
|
+
* start with sgl1". */
|
|
581
|
+
export function readCode(text, now, how = 'long') {
|
|
582
|
+
try { return parseInvite(text, now); } catch (e) {
|
|
583
|
+
if (!(e instanceof MsgError) || !['code_checksum', 'code_length', 'code_version'].includes(e.check)) throw e;
|
|
584
|
+
const as = how === 'parked' ? 'the long code the relay holds for this short code does not parse; ask the inviter for a new one'
|
|
585
|
+
: `read as a long code (it starts sgl1, or has more than 12 characters; a short code has 8, like K7F3-Q9ZP): ${reason(e)}`;
|
|
586
|
+
throw new MsgError(e.check, how === 'parked' ? `${as} (${reason(e)})` : as, { cause: e });
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// A short code is spent once fetched (unpark): a refusal after that would lose the long code it
|
|
591
|
+
// stood for, so the refusal carries it (.long, and in its words). Not when the answer it made
|
|
592
|
+
// still stands (queued, or held by the relay: .kept) nor when the code was answered already.
|
|
593
|
+
export function keepLong(e, long) {
|
|
594
|
+
if (e?.kept || e?.check === 'mailbox_taken') return e;
|
|
595
|
+
const k = new MsgError(e instanceof MsgError ? e.check : 'error', `${e instanceof Error ? reason(e) : String(e)}. The short code is used up; its long code: ${long} (keep this; accept it with the long code)`, { cause: e, http: e?.http });
|
|
596
|
+
k.long = long;
|
|
597
|
+
return k;
|
|
553
598
|
}
|
|
554
599
|
|
|
555
600
|
// Text a relay writes reaches the operator, and perhaps a model, inside this client's messages:
|
|
@@ -580,11 +625,20 @@ async function named(ep, creds, err) {
|
|
|
580
625
|
try {
|
|
581
626
|
const r = await http(`${ep.http}/check`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password }) });
|
|
582
627
|
if (r.body?.ok === false && typeof r.body.check === 'string') {
|
|
583
|
-
|
|
628
|
+
const check = LOGIN_CHECKS.has(r.body.check) ? r.body.check : 'connect';
|
|
629
|
+
return new MsgError(check, `the relay refused the login (${relaySays(`${r.body.check}: ${r.body.detail}`)})${LOGIN_NEXT[check] ? `: ${LOGIN_NEXT[check]}` : ''}`, { cause: err, http: r.http });
|
|
584
630
|
}
|
|
585
631
|
} catch {}
|
|
586
|
-
return err instanceof MsgError ? err : new MsgError('connect', err.message);
|
|
632
|
+
return err instanceof MsgError ? err : new MsgError('connect', `the relay at ${ep.mqtt} did not take the connection (${err.message}): check the network and SIGELO_RELAY / SIGELO_RELAY_ENDPOINTS, then try again`, { cause: err });
|
|
587
633
|
}
|
|
634
|
+
// What to do after a login refusal, by its check (relay/auth.mjs). bundle: sigelo-agent adds the lockout.
|
|
635
|
+
const LOGIN_NEXT = {
|
|
636
|
+
rate: 'too many logins from this network: wait a minute, then try again',
|
|
637
|
+
relay_full: 'the relay is full: try again later',
|
|
638
|
+
challenge_expired: 'the login took longer than its challenge lives (a slow proof of work): try again',
|
|
639
|
+
challenge_unknown: 'try again',
|
|
640
|
+
connect: 'try again later',
|
|
641
|
+
};
|
|
588
642
|
|
|
589
643
|
/**
|
|
590
644
|
* Reads each MQTT packet's fixed header (a type byte, then its length in 1 to 4 bytes of 7 bits,
|
|
@@ -709,12 +763,26 @@ export class Carrier {
|
|
|
709
763
|
// Before anything reads the store: a recovery made by another process (sigelo-agent recover)
|
|
710
764
|
// is seen at once. The store's marks are written first; the state keeps the events.
|
|
711
765
|
if (this.#markRecovered(ctx)) saveState(this.statePath, ctx.st);
|
|
766
|
+
if (this.#lapse(ctx)) saveState(this.statePath, ctx.st);
|
|
712
767
|
const out = fn(ctx);
|
|
768
|
+
// Answers that fn's adds and takes found expired.
|
|
769
|
+
if (this.#lapse(ctx) && !write) saveState(this.statePath, ctx.st);
|
|
713
770
|
if (write) { saveState(this.statePath, ctx.st); ctx.store.commit(); }
|
|
714
771
|
return out;
|
|
715
772
|
});
|
|
716
773
|
}
|
|
717
774
|
#locked(fn) { return this.#with(true, fn); }
|
|
775
|
+
|
|
776
|
+
// An answer that expired before the inviter's reply came: the accept said "waiting", so the next
|
|
777
|
+
// inbox (and contacts until then) says it failed, rather than nothing at all.
|
|
778
|
+
#lapse({ now, store, st }) {
|
|
779
|
+
const gone = store.lapsed(now);
|
|
780
|
+
for (const p of gone) {
|
|
781
|
+
this.#emit(this.#note(st, now, { type: 'pairing_failed', did: p.code_did, name: p.name, code: 'code_expired',
|
|
782
|
+
detail: `the code from ${p.name} expired at ${new Date(p.exp * 1000).toISOString().replace('.000', '')} before the inviter's agent replied: ask the inviter for a new code` }));
|
|
783
|
+
}
|
|
784
|
+
return gone.length > 0;
|
|
785
|
+
}
|
|
718
786
|
#read(fn) { return this.#with(false, fn); }
|
|
719
787
|
|
|
720
788
|
// This agent recovered after it last told a contact of its keys (`announced`: a DID at or before
|
|
@@ -862,7 +930,7 @@ export class Carrier {
|
|
|
862
930
|
if (c.revoked) fail('revoked', `${c.did} was revoked by this owner`);
|
|
863
931
|
} else {
|
|
864
932
|
const hits = this.#liveContacts(store).filter((x) => x.name === to);
|
|
865
|
-
if (hits.length === 0) fail('not_contact', `no contact named ${JSON.stringify(to)}`);
|
|
933
|
+
if (hits.length === 0) fail('not_contact', `no contact named ${JSON.stringify(to)}: contacts lists them; a contact comes from an invite and its accept`);
|
|
866
934
|
if (hits.length > 1) fail('name', `${hits.length} contacts are named ${JSON.stringify(to)}: use the DID`);
|
|
867
935
|
c = hits[0];
|
|
868
936
|
}
|
|
@@ -1591,11 +1659,11 @@ export class Carrier {
|
|
|
1591
1659
|
const { me, proven } = this.#read(({ me, st }) => ({ me, proven: st.relays[relay]?.proven === true }));
|
|
1592
1660
|
const powMax = relay === this.relay ? POW_MAX : POW_MAX_OTHER;
|
|
1593
1661
|
const r = await http(`${ep.http}/challenge?did=${encodeURIComponent(me.current_did)}`);
|
|
1594
|
-
if (r.status === 429)
|
|
1662
|
+
if (r.status === 429) refuse('rate', `the relay ${relay} turned the login away: too many logins from this network (${relaySays(r.body?.error ?? r.body?.detail)}): ${retryIn(r, 'a minute')}, then try again`, r);
|
|
1595
1663
|
// Any other status is no answer about this agent (nginx says 502 while the relay restarts):
|
|
1596
1664
|
// `connect`, retried. `challenge`, which no retry fixes, is a 200 that is not this relay's
|
|
1597
1665
|
// challenge for this agent.
|
|
1598
|
-
if (r.status !== 200)
|
|
1666
|
+
if (r.status !== 200) refuse('connect', `${relay}: ${statusWhy(r, 'GET /challenge')}`, r);
|
|
1599
1667
|
const ch = r.body?.challenge;
|
|
1600
1668
|
if (!exact(ch, ['v', 'typ', 'did', 'relay', 'nonce']) || ch.v !== LOGIN_V || ch.typ !== TYP_LOGIN || typeof ch.nonce !== 'string' || ch.nonce.length > 128) {
|
|
1601
1669
|
fail('challenge', `GET /challenge did not answer a login body {v: "${LOGIN_V}", typ: "${TYP_LOGIN}", did, relay, nonce}`);
|
|
@@ -1807,11 +1875,16 @@ export class Carrier {
|
|
|
1807
1875
|
const creds = await this.#credentials(code.relay, ep);
|
|
1808
1876
|
const r = await http(`${ep.http}/park`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, code_hash: codeHash(s), invite: code.text, exp }) });
|
|
1809
1877
|
const check = typeof r.body?.check === 'string' ? r.body.check : null;
|
|
1810
|
-
if (r.status === 429)
|
|
1811
|
-
if ((r.status === 404 || r.status === 405) && check === null)
|
|
1812
|
-
if (r.status !== 200)
|
|
1813
|
-
|
|
1814
|
-
|
|
1878
|
+
if (r.status === 429) refuse('rate', `the relay ${code.relay} parks no more short codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to an hour')}, or use the long code (invite --long)`, r);
|
|
1879
|
+
if ((r.status === 404 || r.status === 405) && check === null) refuse('park', `the relay ${code.relay} takes no short codes: use the long code (invite --long)`, r);
|
|
1880
|
+
if (r.status !== 200) refuse('connect', `${code.relay}: ${statusWhy(r, 'POST /park')}`, r);
|
|
1881
|
+
// exp is this machine's clock: one far off the relay's is refused (relay/park.mjs PARK_SKEW).
|
|
1882
|
+
const clock = typeof r.body?.detail === 'string' && r.body.detail.startsWith('exp:') ? ': this machine\'s clock may be off (date -u), or use the long code (invite --long)' : '';
|
|
1883
|
+
if (r.body?.ok !== true) refuse(PARK_CHECKS.has(check) ? check : 'park', `the relay refused the short code (${relaySays(`${check}: ${r.body?.detail}`)})${clock}`, r);
|
|
1884
|
+
// The relay keeps the code until its own exp (park.mjs: at most SHORT_TTL by its clock), not
|
|
1885
|
+
// this machine's: that is the one shown. This machine's only when the relay names none.
|
|
1886
|
+
const held = Number.isSafeInteger(r.body.exp) && r.body.exp > 0 ? r.body.exp : exp;
|
|
1887
|
+
return { code: code.text, did: code.did, relay: code.relay, exp: code.exp, short: formatShort(s), short_exp: held };
|
|
1815
1888
|
} catch (e) {
|
|
1816
1889
|
try { this.#locked(({ store }) => store.cancelInvite(code.nonce)); } catch {}
|
|
1817
1890
|
throw e;
|
|
@@ -1822,21 +1895,29 @@ export class Carrier {
|
|
|
1822
1895
|
// GET /park/<code hash>, which the relay answers once. Whatever it answers is a code to parse
|
|
1823
1896
|
// like any other (accept); the four words show whether the pairing is the inviter's.
|
|
1824
1897
|
async unpark(text) {
|
|
1825
|
-
const ep = endpointOf(this.relay, this.endpoints);
|
|
1898
|
+
const shown = formatShort(normaliseShort(text)), ep = endpointOf(this.relay, this.endpoints);
|
|
1826
1899
|
const r = await http(`${ep.http}/park/${codeHash(text)}`);
|
|
1827
|
-
if (r.status === 429)
|
|
1900
|
+
if (r.status === 429) refuse('rate', `the relay ${this.relay} looks up no more short codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to 10 minutes')}, or ask for the long code (invite --long)`, r);
|
|
1828
1901
|
if (r.status === 404 && r.body?.check === 'park_unknown') {
|
|
1829
|
-
|
|
1902
|
+
refuse('park_unknown', `short code ${shown}: no invite waits under it at ${this.relay}. It expired (a short code lives 10 minutes), was used already (once only), or is mistyped; ask the inviter for a new one. If the inviter's agent uses another relay than ${this.relay} (SIGELO_RELAY), ask for the long code (invite --long)`, r);
|
|
1830
1903
|
}
|
|
1831
|
-
if (r.status === 404 || r.status === 405)
|
|
1832
|
-
if (r.status !== 200
|
|
1904
|
+
if (r.status === 404 || r.status === 405) refuse('park', `the relay ${this.relay} takes no short codes: ask the inviter for the long code (invite --long)`, r);
|
|
1905
|
+
if (r.status !== 200) refuse('connect', `${this.relay}: ${statusWhy(r, 'GET /park')}`, r);
|
|
1906
|
+
if (r.body?.ok !== true || typeof r.body.invite !== 'string') refuse('connect', `${this.relay}: GET /park answered 200 without a parked code: try again later; SIGELO_DEBUG=1 shows the answer`, r);
|
|
1833
1907
|
return r.body.invite;
|
|
1834
1908
|
}
|
|
1835
1909
|
|
|
1836
|
-
async accept(text,
|
|
1837
|
-
|
|
1910
|
+
async accept(text, opts = {}) {
|
|
1911
|
+
// Short or long by the input's shape, before either parser runs (short.mjs codeKind).
|
|
1912
|
+
const how = codeKind(text) === 'short' ? 'parked' : 'long';
|
|
1913
|
+
if (how !== 'parked') return this.#answer(text, how, opts);
|
|
1914
|
+
const long = await this.unpark(text);
|
|
1915
|
+
try { return await this.#answer(long, how, opts); } catch (e) { throw keepLong(e, long); }
|
|
1916
|
+
}
|
|
1917
|
+
|
|
1918
|
+
async #answer(text, how, { name, wait = 10 } = {}) {
|
|
1838
1919
|
const { code, id, entry } = this.#locked(({ now, me, store, st }) => {
|
|
1839
|
-
const code =
|
|
1920
|
+
const code = readCode(text, now, how);
|
|
1840
1921
|
// This agent's own relay, and those its operator configured, are the operator's choice.
|
|
1841
1922
|
if (code.relay !== this.relay && !Object.hasOwn(this.endpoints ?? {}, code.relay) && !publicRelay(code.relay)) {
|
|
1842
1923
|
fail('code_relay', `the code names ${code.relay}, an address or a local name, not a public relay: allow it in SIGELO_RELAY_ENDPOINTS if it is yours`);
|
|
@@ -1879,13 +1960,20 @@ export class Carrier {
|
|
|
1879
1960
|
return 'withdrawn';
|
|
1880
1961
|
});
|
|
1881
1962
|
const why = { withdrawn: 'the answer is withdrawn', queued: 'the answer stays queued: it goes at the next connection', delivered: 'the relay holds the answer: the reply is read at a later connection' }[left];
|
|
1882
|
-
|
|
1963
|
+
const err = new MsgError(e.check ?? 'connect', `${reason(e)} (${why})`, { cause: e, http: e.http });
|
|
1964
|
+
if (left !== 'withdrawn') err.kept = true;
|
|
1965
|
+
throw err;
|
|
1883
1966
|
}
|
|
1884
1967
|
const h = this.#handshakes.get(id), sent = this.#results.get(entry);
|
|
1885
1968
|
this.#handshakes.delete(id); this.#results.delete(entry);
|
|
1886
1969
|
if (h?.check) fail(h.check, h.detail);
|
|
1887
1970
|
if (h) return { status: 'connected', contact: h.contact };
|
|
1888
|
-
if (this.#refusedTopics.has(reply)) {
|
|
1971
|
+
if (this.#refusedTopics.has(reply)) {
|
|
1972
|
+
const r = this.#refusedTopics.get(reply);
|
|
1973
|
+
// The reply topic is the code's: held by another identity, someone answered the code first.
|
|
1974
|
+
drop(r.code, r.code === 'mailbox_taken' ? `this code was answered already, by another agent (a code works once): ask the inviter for a new one (${relaySays(r.detail)})`
|
|
1975
|
+
: `the relay did not let this agent claim the reply topic (${relaySays(r.detail)})`);
|
|
1976
|
+
}
|
|
1889
1977
|
if (sent?.code) drop(sent.code, `the relay refused the answer (${relaySays(sent.detail)})`);
|
|
1890
1978
|
if (!sent) return { status: 'pending', did: code.did, relay: code.relay, detail: 'the answer has not reached the relay yet: it goes at the next connection' };
|
|
1891
1979
|
return { status: 'waiting', did: code.did, relay: code.relay, detail: 'answer delivered; the pairing completes when the inviter\'s agent next connects' };
|
|
@@ -1899,6 +1987,8 @@ export class Carrier {
|
|
|
1899
1987
|
re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key) })),
|
|
1900
1988
|
invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
|
|
1901
1989
|
answers: Object.values(s.accepts).filter((p) => p.exp > now).map((p) => ({ name: p.name, did: p.code_did, exp: p.exp, relay: p.relay })),
|
|
1990
|
+
// Pairings that failed since the last inbox, which takes them as events.
|
|
1991
|
+
failed: st.events.filter((e) => e.type === 'pairing_failed').map(({ name, did, code, detail, at }) => ({ name, did, code, detail, at })),
|
|
1902
1992
|
};
|
|
1903
1993
|
});
|
|
1904
1994
|
}
|
|
@@ -1942,7 +2032,7 @@ export class Carrier {
|
|
|
1942
2032
|
return { ids, c };
|
|
1943
2033
|
});
|
|
1944
2034
|
try { await this.#session([c.relay]); } catch (e) {
|
|
1945
|
-
throw new MsgError(e.check ?? 'connect', `${reason(e)} (${ids.length === 1 ? 'the message stays' : `the ${ids.length} messages stay`} queued for ${c.name}: they go at the next connection)
|
|
2035
|
+
throw new MsgError(e.check ?? 'connect', `${reason(e)} (${ids.length === 1 ? 'the message stays' : `the ${ids.length} messages stay`} queued for ${c.name}: they go at the next connection)`, { cause: e, http: e.http });
|
|
1946
2036
|
}
|
|
1947
2037
|
return ids.map((id) => {
|
|
1948
2038
|
const r = this.#results.get(id);
|
|
@@ -1961,7 +2051,7 @@ export class Carrier {
|
|
|
1961
2051
|
const inUse = this.#relaysInUse(), relays = inUse.length > 0 ? inUse : [this.relay];
|
|
1962
2052
|
try {
|
|
1963
2053
|
await this.#session(relays, wait > 0 ? { max: wait * 1000, until: () => this.#read(({ st }) => st.inbox.length > 0) } : {});
|
|
1964
|
-
} catch (e) { offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
|
|
2054
|
+
} catch (e) { this.lastError = e; offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
|
|
1965
2055
|
return this.#locked(({ st }) => {
|
|
1966
2056
|
const out = { messages: st.inbox, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
|
|
1967
2057
|
st.inbox = []; st.events = []; st.dropped = {};
|
|
@@ -1979,7 +2069,7 @@ export class Carrier {
|
|
|
1979
2069
|
this.#routes = new Map();
|
|
1980
2070
|
// Revoked here whatever the relay says; offline: its mailboxes are given up at a later round.
|
|
1981
2071
|
let offline = null;
|
|
1982
|
-
try { await this.#session([c.relay]); } catch (e) { offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
|
|
2072
|
+
try { await this.#session([c.relay]); } catch (e) { this.lastError = e; offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
|
|
1983
2073
|
const released = this.#read(({ st }) => !Object.values(st.relays[c.relay]?.claims ?? {}).some((x) => x.peer === c.did));
|
|
1984
2074
|
return { name: c.name, did: c.did, revoked: true, released, ...(offline && { offline }) };
|
|
1985
2075
|
}
|
package/invite.mjs
CHANGED
|
@@ -45,6 +45,9 @@ const isTime = (t) => Number.isSafeInteger(t) && t >= 0;
|
|
|
45
45
|
// `now` comes from the caller, never from a peer, but NaN or a string would make every expiry
|
|
46
46
|
// comparison false: fail open. Checked at every entry point.
|
|
47
47
|
export const checkTime = (now) => { if (!isTime(now)) fail('now', 'must be Unix seconds'); };
|
|
48
|
+
// For people reading a refusal: an instant, and a span, as words.
|
|
49
|
+
const iso = (t) => new Date(t * 1000).toISOString().replace('.000', '');
|
|
50
|
+
const ago = (s) => (s < 120 ? `${s} s` : s < 7200 ? `${Math.round(s / 60)} minutes` : s < 172800 ? `${Math.round(s / 3600)} hours` : `${Math.round(s / 86400)} days`);
|
|
48
51
|
|
|
49
52
|
// ---------------------------------------------------------------- the code
|
|
50
53
|
|
|
@@ -128,26 +131,30 @@ export function parseInvite(text, now) {
|
|
|
128
131
|
// Only another version's prefix is a version error. Any other start ("sgI1", "Sgl1", a lost
|
|
129
132
|
// first character) is a typo, and reads as one, like a typo among the digits.
|
|
130
133
|
if (typeof text === 'string' && /^sgl[02-9]/.test(text)) fail('code_version', `a ${text.slice(0, 4)} code; this library reads ${PREFIX}`);
|
|
131
|
-
if (typeof text !== 'string' || !text.startsWith(PREFIX)) fail('code_checksum', `does not start with ${PREFIX}:
|
|
134
|
+
if (typeof text !== 'string' || !text.startsWith(PREFIX)) fail('code_checksum', `it does not start with ${PREFIX}: paste the whole code, from ${PREFIX} to its last character`);
|
|
132
135
|
const digits = text.slice(PREFIX.length);
|
|
133
|
-
if (digits.length === 0 || digits.length > MAX_DIGITS) fail('code_length', `${digits.length}
|
|
134
|
-
|
|
136
|
+
if (digits.length === 0 || digits.length > MAX_DIGITS) fail('code_length', `${digits.length} characters after ${PREFIX}, ${digits.length === 0 ? 'none' : `at most ${MAX_DIGITS}`}: not the whole code, or two codes run together`);
|
|
137
|
+
let at = PREFIX.length;
|
|
138
|
+
for (const ch of digits) {
|
|
139
|
+
at++;
|
|
140
|
+
if (!B58.includes(ch)) fail('code_checksum', `character ${at} ${JSON.stringify(ch)} is not in a long code (base58: no 0, O, I or l): a typo; copy the code, do not retype it`);
|
|
141
|
+
}
|
|
135
142
|
const b = b58decode(digits);
|
|
136
|
-
if (b.length < 5) fail('code_length', `${b.length} bytes`);
|
|
143
|
+
if (b.length < 5) fail('code_length', `${b.length} bytes, too short for a code: not the whole code`);
|
|
137
144
|
// The checksum first: it sits at the end whatever the layout, so a typo reads as a typo even
|
|
138
145
|
// when it hits the version or the length byte.
|
|
139
146
|
const sum = sha256(b.subarray(0, b.length - 4));
|
|
140
|
-
for (let i = 0; i < 4; i++) if (sum[i] !== b[b.length - 4 + i]) fail('code_checksum', 'does not match: a
|
|
147
|
+
for (let i = 0; i < 4; i++) if (sum[i] !== b[b.length - 4 + i]) fail('code_checksum', 'its checksum does not match: a character is wrong, missing or extra; copy the whole code again, do not retype it');
|
|
141
148
|
if (b[0] !== VERSION) fail('code_version', `version ${b[0]}, this library reads ${VERSION}`);
|
|
142
149
|
const n = b.length > AT_RLEN ? b[AT_RLEN] : 0;
|
|
143
|
-
if (n < 1 || n > RELAY_MAX || b.length !== FIXED + n) fail('code_length', `${b.length} bytes with a relay length of ${n}`);
|
|
150
|
+
if (n < 1 || n > RELAY_MAX || b.length !== FIXED + n) fail('code_length', `${b.length} bytes with a relay length of ${n}: not a code this library makes`);
|
|
144
151
|
const relay = String.fromCharCode(...b.subarray(AT_RELAY, AT_RELAY + n));
|
|
145
152
|
checkRelay(relay);
|
|
146
153
|
const exp = new DataView(b.buffer, b.byteOffset).getUint32(AT_EXP);
|
|
147
|
-
if (now >= exp) fail('code_expired', `expired at ${exp}`);
|
|
154
|
+
if (now >= exp) fail('code_expired', `it expired at ${iso(exp)}, ${ago(now - exp)} ago by this machine's clock (${iso(now)}): ask for a new code; if it was made just now, this clock is wrong (date -u)`);
|
|
148
155
|
// No inviter makes a code for longer than 7 days. A longer one would keep Bob's one-time secret
|
|
149
156
|
// and key in his store for as long as it says.
|
|
150
|
-
if (exp - now > TTL_MAX + SKEW) fail('code_ttl', `expires ${exp - now}
|
|
157
|
+
if (exp - now > TTL_MAX + SKEW) fail('code_ttl', `it expires at ${iso(exp)}, ${ago(exp - now)} from now by this machine's clock (${iso(now)}), and a code lives at most 7 days: this clock is behind (date -u), or the code was not made by sigelo`);
|
|
151
158
|
const secret = b.slice(AT_SECRET, AT_EXP);
|
|
152
159
|
return { did: 'did:sigelo:' + multibase(b.slice(AT_DID, AT_SECRET)), secret, exp, relay, bytes: b, text, nonce: inviteNonce(b) };
|
|
153
160
|
}
|
package/kdf.mjs
CHANGED
|
@@ -10,8 +10,16 @@ export const MSG_V = 'sigelo-msg/0';
|
|
|
10
10
|
|
|
11
11
|
// Every refusal in contact/ names its check, as accept/node/sigelo-pair.mjs's PairingError does:
|
|
12
12
|
// one class for invite, envelope, prekeys and carrier, so a caller catches MsgError and reads .check.
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
// extra, for whoever debugs (SIGELO_DEBUG=1 prints it): cause, the error underneath; http, the
|
|
14
|
+
// relay's answer ({ url, status, body }).
|
|
15
|
+
export class MsgError extends Error {
|
|
16
|
+
constructor(check, why, extra) {
|
|
17
|
+
super(`${check}: ${why}`, extra?.cause === undefined ? undefined : { cause: extra.cause });
|
|
18
|
+
this.check = check;
|
|
19
|
+
if (extra?.http) this.http = extra.http;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export const fail = (check, why, extra) => { throw new MsgError(check, why, extra); };
|
|
15
23
|
|
|
16
24
|
export const hex = (b) => bytesToHex(b);
|
|
17
25
|
export function unhex(s, len, check) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sigelo-contact",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
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": [
|
|
@@ -82,6 +82,6 @@
|
|
|
82
82
|
"@noble/hashes": "^2.4.0",
|
|
83
83
|
"@noble/post-quantum": "^0.7.1",
|
|
84
84
|
"mqtt": "^5.16.0",
|
|
85
|
-
"sigelo": "^0.1.
|
|
85
|
+
"sigelo": "^0.1.6"
|
|
86
86
|
}
|
|
87
87
|
}
|
package/short.mjs
CHANGED
|
@@ -18,7 +18,8 @@
|
|
|
18
18
|
// The four words: once a pairing completes, both sides derive them from `pair` (kdf.pairId, which
|
|
19
19
|
// binds the pairing key K and so both original DIDs): HKDF-SHA256(pair's 16 bytes, salt
|
|
20
20
|
// "sigelo-fingerprint/0", empty info, 6 bytes); the first 44 bits, 11 at a time, index the BIP-39
|
|
21
|
-
// English list. The same words on both sides =
|
|
21
|
+
// English list. The same words on both sides = no mix-up and no casual swap; a relay that invests
|
|
22
|
+
// GPU time in one is caught by the pair id (THREAT-MODEL.md §2.10).
|
|
22
23
|
import { randomBytes } from 'node:crypto';
|
|
23
24
|
import { hkdf } from '@noble/hashes/hkdf.js';
|
|
24
25
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
@@ -32,16 +33,40 @@ export const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
|
32
33
|
export const SHORT_TTL = 600, SHORT_LENGTH = 8;
|
|
33
34
|
const FOLD = { I: '1', L: '1', O: '0' };
|
|
34
35
|
// Whitespace, and the hyphen with every dash a phone or a word processor puts in its place.
|
|
35
|
-
const SEPARATORS = /[\s
|
|
36
|
+
const SEPARATORS = /[\s\-\u2010-\u2015\u2212]+/g, SEPARATOR = /^[\s\-\u2010-\u2015\u2212]$/;
|
|
36
37
|
// Longer input is no short code: refused before any work.
|
|
37
38
|
const MAX_INPUT = 64;
|
|
39
|
+
// Short or long is decided on the input's shape, before either parser runs: a short code mistyped
|
|
40
|
+
// (7 characters, a U, a full stop after it) read as a long code was refused as "does not start
|
|
41
|
+
// with sgl1", which tells the person nothing. A long code is about 126 characters and starts sgl1.
|
|
42
|
+
export const SHORT_MAX = 12;
|
|
43
|
+
/** 'short' when `text`, without spaces and dashes, is at most SHORT_MAX characters and does not
|
|
44
|
+
* start with sgl1; else 'long'. Says how the code is read, not whether it is good. */
|
|
45
|
+
export function codeKind(text) {
|
|
46
|
+
const s = typeof text === 'string' ? text.replace(SEPARATORS, '') : '';
|
|
47
|
+
return s.length <= SHORT_MAX && !/^sgl1/i.test(s) ? 'short' : 'long';
|
|
48
|
+
}
|
|
49
|
+
const READ = 'read as a short code (12 characters or fewer, no sgl1)';
|
|
50
|
+
const AGAIN = 'check it with whoever gave it to you';
|
|
38
51
|
|
|
39
|
-
/** The canonical form of a short code ("K7F3Q9ZP"), or throws short_code. */
|
|
52
|
+
/** The canonical form of a short code ("K7F3Q9ZP"), or throws short_code naming the character at fault. */
|
|
40
53
|
export function normaliseShort(text) {
|
|
41
54
|
if (typeof text !== 'string' || text.length > MAX_INPUT) fail('short_code', 'not a short code');
|
|
55
|
+
const shown = JSON.stringify(text.trim());
|
|
56
|
+
// Positions count the characters a person typed, separators left out: "character 5" of K7F3-U9ZP is the U.
|
|
57
|
+
let at = 0;
|
|
58
|
+
for (const c of text) {
|
|
59
|
+
if (SEPARATOR.test(c)) continue;
|
|
60
|
+
at++;
|
|
61
|
+
const u = c.toUpperCase();
|
|
62
|
+
if (!ALPHABET.includes(FOLD[u] ?? u)) {
|
|
63
|
+
fail('short_code', `${shown} ${READ}: character ${at} ${JSON.stringify(c)} is not in the alphabet; a short code uses 0-9 and A-Z without I, L, O, U${u === 'U' ? ' (a V?)' : ''}: ${AGAIN}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
42
66
|
const s = text.replace(SEPARATORS, '').toUpperCase().replace(/[ILO]/g, (c) => FOLD[c]);
|
|
43
|
-
if (s.length !== SHORT_LENGTH)
|
|
44
|
-
|
|
67
|
+
if (s.length !== SHORT_LENGTH) {
|
|
68
|
+
fail('short_code', `${shown} ${READ}: ${s.length} characters, a short code has ${SHORT_LENGTH} (like K7F3-Q9ZP): ${Math.abs(SHORT_LENGTH - s.length)} ${s.length < SHORT_LENGTH ? 'missing' : 'too many'}; ${AGAIN}`);
|
|
69
|
+
}
|
|
45
70
|
return s;
|
|
46
71
|
}
|
|
47
72
|
|
package/store.mjs
CHANGED
|
@@ -58,12 +58,29 @@ export class Contacts {
|
|
|
58
58
|
|
|
59
59
|
// Expired invites and answers go, with the one-time secret and kem_sk they hold, whenever an
|
|
60
60
|
// entry is added or taken, as sigelo-pair's issue() drops expired challenges. Returns how many.
|
|
61
|
+
// An expired answer is a pairing that never completed: kept, without its secrets, for lapsed().
|
|
61
62
|
#purge(now) {
|
|
62
63
|
let n = 0;
|
|
63
|
-
for (const k of ['invites', 'accepts'])
|
|
64
|
+
for (const k of ['invites', 'accepts']) {
|
|
65
|
+
for (const [nonce, p] of Object.entries(this.s[k])) {
|
|
66
|
+
if (p.exp > now) continue;
|
|
67
|
+
if (k === 'accepts') (this.gone ??= []).push({ id: nonce, code_did: p.code_did, name: p.name, exp: p.exp, relay: p.relay });
|
|
68
|
+
delete this.s[k][nonce]; n++;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
64
71
|
return n;
|
|
65
72
|
}
|
|
66
73
|
|
|
74
|
+
/** The answers that expired unanswered, purged now or at an add or take since the last call: once each. */
|
|
75
|
+
lapsed(now) {
|
|
76
|
+
checkTime(now);
|
|
77
|
+
this.load();
|
|
78
|
+
if (this.#purge(now)) this.save();
|
|
79
|
+
const g = this.gone ?? [];
|
|
80
|
+
this.gone = [];
|
|
81
|
+
return g;
|
|
82
|
+
}
|
|
83
|
+
|
|
67
84
|
// max: TTL_MAX for the owner's own codes. The code does not say when it was made, so on the
|
|
68
85
|
// answering side a 7-day code read on a clock a little behind gets SKEW more.
|
|
69
86
|
#add(kind, nonce, entry, now, max) {
|
package/test-carrier.mjs
CHANGED
|
@@ -1045,7 +1045,10 @@ try {
|
|
|
1045
1045
|
const code = (await hana.invite({ name: 'ivan' })).code;
|
|
1046
1046
|
ok((await ivan.accept(code, { name: 'hana', wait: 0.3 })).status === 'waiting', 'ivan answers the code of hana, whose bundle holds 30 KB of attestations');
|
|
1047
1047
|
const hb = await hana.inbox();
|
|
1048
|
-
|
|
1048
|
+
// Her two answers to the hop codes above (queued, never delivered) expired meanwhile: said once each.
|
|
1049
|
+
const lapsed = hb.events.filter((e) => e.code === 'code_expired');
|
|
1050
|
+
ok(kinds({ events: hb.events.filter((e) => e.code !== 'code_expired') }) === 'paired' && lapsed.length === 2 && lapsed.every((e) => e.type === 'pairing_failed' && e.did === lapsed[0].did)
|
|
1051
|
+
&& seen('hana', (e) => e.type === 'refused').length === 0, `hana pairs and the relay takes her reply, which carries her chain only; her two hop answers reported expired (${kinds(hb)})`);
|
|
1049
1052
|
ok((await ivan.inbox()).events.some((e) => e.type === 'paired' && e.did === H.original), 'ivan pairs');
|
|
1050
1053
|
}
|
|
1051
1054
|
{
|
package/test-short.mjs
CHANGED
|
@@ -13,12 +13,14 @@ import { dirname, join } from 'node:path';
|
|
|
13
13
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
14
14
|
import { keygen } from 'sigelo';
|
|
15
15
|
import { BIP39_SHA256, WORDS } from './bip39-english.mjs';
|
|
16
|
-
import {
|
|
16
|
+
import { makeInvite } from './invite.mjs';
|
|
17
|
+
import { ALPHABET, SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, isShort, makeShort, normaliseShort } from './short.mjs';
|
|
17
18
|
|
|
18
19
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
19
20
|
let count = 0;
|
|
20
21
|
const fails = [];
|
|
21
22
|
const ok = (cond, what) => { count++; if (!cond) fails.push(what); };
|
|
23
|
+
const messageOf = (f) => { try { f(); return 'accepted'; } catch (e) { return e.message; } };
|
|
22
24
|
const checkOf = (f) => { try { f(); return 'accepted'; } catch (e) { return e.check ?? `exception ${e.constructor.name}: ${e.message}`; } };
|
|
23
25
|
const report = () => {
|
|
24
26
|
for (const f of fails) console.log('FAIL ' + f);
|
|
@@ -54,6 +56,38 @@ const report = () => {
|
|
|
54
56
|
ok(SHORT_TTL === 600, 'a short code lives 10 minutes');
|
|
55
57
|
}
|
|
56
58
|
|
|
59
|
+
// ================================================================ refusals a person can act on
|
|
60
|
+
// Short or long is decided on the shape, before either parser runs; each refusal says how the code
|
|
61
|
+
// was read, names the character at fault, and says what to do.
|
|
62
|
+
{
|
|
63
|
+
for (const [t, kind] of [['K7F3-Q9ZP', 'short'], ['k7f3 q9z', 'short'], ['K7F3-Q9ZP.', 'short'], ['', 'short'], ['K7F3-Q9ZP-ABC', 'short'], ['K7F3Q9ZPABCDE', 'long'], ['sgl1abc', 'long'], ['SGL1ABC', 'long'], ['x'.repeat(126), 'long']]) {
|
|
64
|
+
ok(codeKind(t) === kind, `codeKind ${JSON.stringify(t)}: ${codeKind(t)}, expected ${kind}`);
|
|
65
|
+
}
|
|
66
|
+
const u = messageOf(() => normaliseShort('K7F3-U9ZP'));
|
|
67
|
+
ok(u.startsWith('short_code: "K7F3-U9ZP" read as a short code') && u.includes('character 5 "U" is not in the alphabet; a short code uses 0-9 and A-Z without I, L, O, U'), `a U: its position named (${u})`);
|
|
68
|
+
const seven = messageOf(() => normaliseShort('K7F3-Q9Z'));
|
|
69
|
+
ok(seven.includes('7 characters, a short code has 8 (like K7F3-Q9ZP): 1 missing'), `7 characters: said (${seven})`);
|
|
70
|
+
const nine = messageOf(() => normaliseShort('K7F3 Q9ZPX'));
|
|
71
|
+
ok(nine.includes('9 characters, a short code has 8 (like K7F3-Q9ZP): 1 too many'), `9 characters: said (${nine})`);
|
|
72
|
+
const dot = messageOf(() => normaliseShort('k7f3-q9zp.'));
|
|
73
|
+
ok(dot.includes('character 9 "." is not in the alphabet'), `a leftover character: its position named (${dot})`);
|
|
74
|
+
const { readCode } = await import('./carrier.mjs');
|
|
75
|
+
const t0 = Date.parse('2026-10-14T12:00:00Z') / 1000, D = keygen({ seed: new Uint8Array(32), recovery: 'sha256:' + '0'.repeat(64) }).did;
|
|
76
|
+
const long = messageOf(() => readCode('hello-world-this-is-long', t0));
|
|
77
|
+
ok(long.startsWith('code_checksum: read as a long code (it starts sgl1, or has more than 12 characters') && long.includes('paste the whole code'), `a long input without sgl1: read as a long code, said (${long})`);
|
|
78
|
+
const code = makeInvite({ did: D, relay: 'relay.test', now: t0, ttl: 600 }).text;
|
|
79
|
+
const typo = messageOf(() => readCode(code.slice(0, 40) + (code[40] === 'A' ? 'B' : 'A') + code.slice(41), t0));
|
|
80
|
+
ok(typo.startsWith('code_checksum: read as a long code') && typo.includes('checksum does not match') && typo.includes('do not retype it'), `a long code with a typo: the checksum, and what to do (${typo})`);
|
|
81
|
+
const bad = messageOf(() => readCode(code.slice(0, 40) + '0' + code.slice(41), t0));
|
|
82
|
+
ok(bad.includes('character 41 "0" is not in a long code'), `a long code with a 0: its position named (${bad})`);
|
|
83
|
+
const late = messageOf(() => readCode(code, t0 + 3600));
|
|
84
|
+
ok(late.startsWith('code_expired: it expired at 2026-10-14T12:10:00Z, 50 minutes ago by this machine\'s clock') && late.includes('date -u'), `an expired code: when, by which clock, what to do (${late})`);
|
|
85
|
+
const skew = messageOf(() => readCode(makeInvite({ did: D, relay: 'relay.test', now: t0, ttl: 7 * 86400 }).text, t0 - 3 * 86400));
|
|
86
|
+
ok(skew.startsWith('code_ttl:') && skew.includes('this clock is behind (date -u)'), `a code living past 7 days by this clock: clock skew said (${skew})`);
|
|
87
|
+
const parked = messageOf(() => readCode('sgl1abc', t0, 'parked'));
|
|
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
|
+
}
|
|
90
|
+
|
|
57
91
|
const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', 'relay');
|
|
58
92
|
if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
|
|
59
93
|
report();
|
|
@@ -86,6 +120,7 @@ const make = (a) => {
|
|
|
86
120
|
return new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...pathsFor(join(dir, `${a.label}.local.json`)), relay: HOST, endpoints,
|
|
87
121
|
clock: () => now, onEvent: (e) => events[a.label].push(e), keep: true, backoff: [100, 400], retentionDays: 7 });
|
|
88
122
|
};
|
|
123
|
+
const failure = async (f) => { try { await f(); return { check: 'accepted', message: 'accepted' }; } catch (e) { return e; } };
|
|
89
124
|
const refused = async (f) => { try { await f(); return 'accepted'; } catch (e) { return e.check ?? `exception ${e.message}`; } };
|
|
90
125
|
try {
|
|
91
126
|
const alice = agent('alice'), bob = agent('bob'), carol = agent('carol');
|
|
@@ -108,7 +143,14 @@ try {
|
|
|
108
143
|
// One use: carol tries the same code.
|
|
109
144
|
ok(await refused(() => cc.accept(inv.short, { wait: 1 })) === 'park_unknown', 'the same short code a second time: park_unknown');
|
|
110
145
|
// A code nobody parked.
|
|
111
|
-
|
|
146
|
+
const nobody = formatShort(makeShort());
|
|
147
|
+
ok(await refused(() => cc.accept(nobody, { wait: 1 })) === 'park_unknown', 'a code nobody parked: park_unknown');
|
|
148
|
+
const pu = await failure(() => cc.accept(nobody.toLowerCase(), { wait: 1 }));
|
|
149
|
+
ok(pu.check === 'park_unknown' && pu.message.includes(`short code ${nobody}: no invite waits under it at ${HOST}`) && pu.message.includes('expired (a short code lives 10 minutes), was used already (once only), or is mistyped; ask the inviter for a new one')
|
|
150
|
+
&& pu.message.includes('another relay') && pu.http?.status === 404, `park_unknown: the code, the relay, the three reasons, the next step, another relay; the answer kept for SIGELO_DEBUG (${pu.message})`);
|
|
151
|
+
// A mistyped short code is refused before anything connects, as a short code.
|
|
152
|
+
const mt = await failure(() => cc.accept('K7F3-Q9Z', { wait: 1 }));
|
|
153
|
+
ok(mt.check === 'short_code' && mt.message.includes('7 characters, a short code has 8'), `carrier.accept of 7 characters: short_code, not code_checksum (${mt.message})`);
|
|
112
154
|
// Expiry: parked, then 10 minutes and a second pass.
|
|
113
155
|
const late = await ca.invite({ name: 'carol', short: true });
|
|
114
156
|
now += SHORT_TTL;
|
|
@@ -116,9 +158,32 @@ try {
|
|
|
116
158
|
// An inviter whose clock runs a minute ahead of the relay's still parks (relay/park.mjs PARK_SKEW).
|
|
117
159
|
const ahead = new Carrier({ identity: () => ({ secret: alice.secret, bundle: alice.bundle }), ...pathsFor(join(dir, 'alice.local.json')), relay: HOST, endpoints,
|
|
118
160
|
clock: () => now + 60, keep: true, backoff: [100, 400], retentionDays: 7 });
|
|
119
|
-
|
|
161
|
+
let fastInv = {}, fast = 'accepted';
|
|
162
|
+
try { fastInv = await ahead.invite({ name: 'carol', short: true }); } catch (e) { fast = e.check ?? `exception ${e.message}`; }
|
|
120
163
|
ok(fast === 'accepted', `an inviter's clock a minute ahead of the relay's: the short code parks (${fast})`);
|
|
164
|
+
ok(fastInv.short_exp === now + SHORT_TTL, `short_exp is the relay's exp (${now + SHORT_TTL}), not the fast clock's (${now + 60 + SHORT_TTL}): ${fastInv.short_exp}`);
|
|
121
165
|
await ahead.stop();
|
|
166
|
+
// An inviter's clock an hour ahead: the relay refuses the parking, and the refusal says the clock.
|
|
167
|
+
const far = new Carrier({ identity: () => ({ secret: alice.secret, bundle: alice.bundle }), ...pathsFor(join(dir, 'alice.local.json')), relay: HOST, endpoints,
|
|
168
|
+
clock: () => now + 3600, keep: true, backoff: [100, 400], retentionDays: 7 });
|
|
169
|
+
const fa = await failure(() => far.invite({ name: 'carol', short: true }));
|
|
170
|
+
ok(fa.check === 'park' && fa.message.includes('this machine\'s clock may be off (date -u)'), `an inviter's clock an hour ahead: park refused, the clock named (${fa.message})`);
|
|
171
|
+
await far.stop();
|
|
172
|
+
// A short code is spent once fetched: a refusal after that carries the long code it stood for.
|
|
173
|
+
// erin's clock is an hour ahead, past the long code's two minutes: code_expired after the fetch.
|
|
174
|
+
const erin = agent('erin'), brief = await ca.invite({ name: 'erin', ttl: 120, short: true });
|
|
175
|
+
const skewed = new Carrier({ identity: () => ({ secret: erin.secret, bundle: erin.bundle }), ...pathsFor(join(dir, 'erin.local.json')), relay: HOST, endpoints,
|
|
176
|
+
clock: () => now + 3600, keep: true, backoff: [100, 400], retentionDays: 7 });
|
|
177
|
+
const kept = await failure(() => skewed.accept(brief.short, { wait: 1 }));
|
|
178
|
+
ok(kept.check === 'code_expired' && kept.long === brief.code && kept.message.includes(`its long code: ${brief.code} (keep this; accept it with the long code)`),
|
|
179
|
+
`refused after the short code was fetched: the long code in the refusal and as .long (${kept.message})`);
|
|
180
|
+
await skewed.stop();
|
|
181
|
+
const ce = make(erin);
|
|
182
|
+
await ca.start();
|
|
183
|
+
const kr = await ce.accept(kept.long, { name: 'alice', wait: 20 });
|
|
184
|
+
await ca.stop();
|
|
185
|
+
ok(kr.status === 'connected', `the kept long code, accepted with a right clock: connected (${kr.status})`);
|
|
186
|
+
await ce.stop();
|
|
122
187
|
// --long: no parking at all.
|
|
123
188
|
const long = await ca.invite({ name: 'carol', short: false });
|
|
124
189
|
ok(long.short === undefined && /^sgl1/.test(long.code), 'invite without a short code (--long): the long code only');
|
|
@@ -128,6 +193,30 @@ try {
|
|
|
128
193
|
await ca.stop();
|
|
129
194
|
ok(rl.status === 'connected' && rl.contact.fingerprint === wordsOf(ca, carol.did), 'accept by the long code: connected, the same four words on both sides');
|
|
130
195
|
ok(rl.contact.fingerprint !== r.contact.fingerprint, 'another pairing, other words');
|
|
196
|
+
// The same long code a second time, by another agent: answered already, said so.
|
|
197
|
+
const dave = agent('dave'), cd = make(dave);
|
|
198
|
+
const again = await failure(() => cd.accept(long.code, { name: 'alice', wait: 3 }));
|
|
199
|
+
ok(again.check === 'mailbox_taken' && again.message.includes('this code was answered already, by another agent (a code works once): ask the inviter for a new one'), `a long code answered before: said so (${again.message})`);
|
|
200
|
+
await cd.stop();
|
|
201
|
+
// The relay's brake on lookups: rate, and when to try again.
|
|
202
|
+
let rate = null;
|
|
203
|
+
for (let i = 0; i < 30 && rate === null; i++) { const e = await failure(() => cd.unpark(formatShort(makeShort()))); if (e.check === 'rate') rate = e; }
|
|
204
|
+
ok(rate !== null && rate.message.includes(`wait ${600 - (now % 600)} s, or ask for the long code`) && rate.http?.status === 429, `lookups past the relay's brake: rate, and the relay's Retry-After as when to try again (${rate?.message})`);
|
|
205
|
+
// An answer that outlives its code, the inviter offline throughout: accept said waiting; then
|
|
206
|
+
// contacts and the next inbox say the pairing failed (code_expired), once, in one line.
|
|
207
|
+
const frank = agent('frank'), cf = make(frank), brief2 = await ca.invite({ name: 'frank', ttl: 120, short: false });
|
|
208
|
+
const fw = await cf.accept(brief2.code, { name: 'alice', wait: 1 });
|
|
209
|
+
ok(fw.status === 'waiting' && cf.contacts().answers.length === 1 && cf.contacts().failed.length === 0, `accept with the inviter offline: waiting, one answer (${fw.status})`);
|
|
210
|
+
now += 121;
|
|
211
|
+
const lc = cf.contacts(), lf = lc.failed[0];
|
|
212
|
+
ok(lc.answers.length === 0 && lc.failed.length === 1 && lf.code === 'code_expired' && lf.name === 'alice' && lf.did === alice.did
|
|
213
|
+
&& lf.detail === `the code from alice expired at ${new Date(brief2.exp * 1000).toISOString().replace('.000', '')} before the inviter's agent replied: ask the inviter for a new code`,
|
|
214
|
+
`contacts after the code's expiry: the answer gone, failed lists it (code_expired, the time, what to do): ${JSON.stringify(lc.failed)}`);
|
|
215
|
+
ok(events.frank.filter((e) => e.type === 'pairing_failed' && e.code === 'code_expired').length === 1, 'onEvent: one pairing_failed code_expired');
|
|
216
|
+
const lb = await cf.inbox({ wait: 0 });
|
|
217
|
+
ok(lb.events.filter((e) => e.type === 'pairing_failed' && e.code === 'code_expired' && e.did === alice.did).length === 1, `the next inbox reports it once (${JSON.stringify(lb.events)})`);
|
|
218
|
+
ok(cf.contacts().failed.length === 0 && (await cf.inbox({ wait: 0 })).events.every((e) => e.type !== 'pairing_failed'), 'and then neither contacts nor inbox again');
|
|
219
|
+
await cf.stop();
|
|
131
220
|
// The database holds no short code and no long code (memory only).
|
|
132
221
|
const dump = readFileSync(join(dir, 'relay.db')).toString('latin1') + (existsSync(join(dir, 'relay.db-wal')) ? readFileSync(join(dir, 'relay.db-wal')).toString('latin1') : '');
|
|
133
222
|
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');
|