sigelo-contact 0.1.4 → 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/README.md +2 -2
- package/bip39-english.mjs +283 -0
- package/carrier.mjs +154 -29
- package/fixtures/short-code-v0.json +167 -0
- package/gen-short.mjs +92 -0
- package/invite.mjs +15 -8
- package/kdf.mjs +10 -2
- package/package.json +12 -5
- package/short.mjs +101 -0
- package/store.mjs +18 -1
- package/test-carrier.mjs +4 -1
- package/test-short.mjs +229 -0
package/carrier.mjs
CHANGED
|
@@ -4,13 +4,18 @@
|
|
|
4
4
|
// sees random topics and ciphertext; everything here that decides who someone is runs offline.
|
|
5
5
|
//
|
|
6
6
|
// const c = new Carrier({ identity, store, state, relay, endpoints, retentionDays, clock, onEvent, keep })
|
|
7
|
-
// await c.invite({ name, ttl })
|
|
8
|
-
//
|
|
9
|
-
// c.
|
|
7
|
+
// await c.invite({ name, ttl, short }) → { code, did, relay, exp, short?, short_exp? } the answer topic is claimed first;
|
|
8
|
+
// short: the long code is also parked at the relay under a short one
|
|
9
|
+
// await c.unpark(short) → the long code parked under a short one, taken from the relay (one use)
|
|
10
|
+
// await c.accept(code, { name, wait }) → { status: 'connected' | 'waiting' | 'pending', … } a long code or a short one
|
|
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
|
|
10
14
|
// await c.send(to, content, { label }) → { status: 'sent' | 'queued', … }, or throws the relay's code
|
|
11
15
|
// await c.sendAll(to, contents, { label }) → one result each ('refused' with its code), one login
|
|
12
16
|
// await c.inbox({ wait }) → { messages, events, dropped, offline? }: all are taken (messages: those kept)
|
|
13
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)
|
|
14
19
|
// await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
|
|
15
20
|
//
|
|
16
21
|
// identity() → { secret, bundle }: the agent's current secret key and SPEC §8 bundle, read again at
|
|
@@ -149,6 +154,7 @@ import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, inviteKeys,
|
|
|
149
154
|
import { MsgError, checkNow, fail, hex, isoWeek, pairId, topic } from './kdf.mjs';
|
|
150
155
|
import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
|
|
151
156
|
import { Contacts } from './store.mjs';
|
|
157
|
+
import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, makeShort, normaliseShort } from './short.mjs';
|
|
152
158
|
|
|
153
159
|
export const V = 'sigelo-carrier/0';
|
|
154
160
|
export const DEFAULT_RELAY = 'relay.sigelo.ai', MQTT_PORT = 8883, NOTICE = '$sigelo/notice';
|
|
@@ -256,6 +262,10 @@ const b64 = (b) => Buffer.from(b).toString('base64');
|
|
|
256
262
|
const unb64 = (s) => new Uint8Array(Buffer.from(s, 'base64'));
|
|
257
263
|
const randomId = () => hex(randomBytes(8));
|
|
258
264
|
const clientIdOf = (original) => 's' + createHash('sha256').update(original, 'utf8').digest('hex').slice(0, 24);
|
|
265
|
+
// The four words of a pairing (short.mjs), from its pairing key as the store holds it (hex), or null.
|
|
266
|
+
const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
|
|
267
|
+
// The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
|
|
268
|
+
const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_CHECKS]);
|
|
259
269
|
|
|
260
270
|
// ---------------------------------------------------------------- configuration
|
|
261
271
|
|
|
@@ -312,7 +322,7 @@ export function optionsFromEnv(env = process.env) {
|
|
|
312
322
|
const o = {};
|
|
313
323
|
if (env.SIGELO_RELAY) o.relay = env.SIGELO_RELAY;
|
|
314
324
|
if (env.SIGELO_RELAY_ENDPOINTS) {
|
|
315
|
-
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://…"}}'); }
|
|
316
326
|
}
|
|
317
327
|
if (env.SIGELO_RELAY_RETENTION_DAYS) {
|
|
318
328
|
const n = Number(env.SIGELO_RELAY_RETENTION_DAYS);
|
|
@@ -521,28 +531,70 @@ export async function solvePow(host, original, nonce, bits, deadline = Infinity)
|
|
|
521
531
|
// past publicRelay's check on the code's host. A relay never needs one: `connect`.
|
|
522
532
|
async function http(url, init = {}) {
|
|
523
533
|
let res;
|
|
524
|
-
|
|
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;
|
|
525
540
|
if ((res.status >= 300 && res.status < 400) || res.type === 'opaqueredirect') {
|
|
526
541
|
try { await res.body?.cancel(); } catch {}
|
|
527
|
-
fail('connect', `${
|
|
542
|
+
fail('connect', `${at}: answered ${res.status}, a redirect, which this client does not follow`, { http });
|
|
528
543
|
}
|
|
529
|
-
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 });
|
|
530
545
|
const chunks = [];
|
|
531
546
|
let n = 0;
|
|
532
547
|
try {
|
|
533
548
|
// Leaving the loop by a throw cancels the stream: nothing more is read.
|
|
534
549
|
for await (const chunk of res.body ?? []) {
|
|
535
550
|
n += chunk.length;
|
|
536
|
-
if (n > HTTP_MAX) fail('connect', `${
|
|
551
|
+
if (n > HTTP_MAX) fail('connect', `${at}: answer over ${HTTP_MAX} bytes`, { http });
|
|
537
552
|
chunks.push(chunk);
|
|
538
553
|
}
|
|
539
554
|
} catch (e) {
|
|
540
555
|
if (e instanceof MsgError) throw e;
|
|
541
|
-
fail('connect', `${
|
|
556
|
+
fail('connect', `${at}: the answer broke off (${e.cause?.code ?? e.message}): try again`, { cause: e, http });
|
|
542
557
|
}
|
|
543
558
|
let body = null;
|
|
544
|
-
|
|
545
|
-
|
|
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;
|
|
546
598
|
}
|
|
547
599
|
|
|
548
600
|
// Text a relay writes reaches the operator, and perhaps a model, inside this client's messages:
|
|
@@ -573,11 +625,20 @@ async function named(ep, creds, err) {
|
|
|
573
625
|
try {
|
|
574
626
|
const r = await http(`${ep.http}/check`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password }) });
|
|
575
627
|
if (r.body?.ok === false && typeof r.body.check === 'string') {
|
|
576
|
-
|
|
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 });
|
|
577
630
|
}
|
|
578
631
|
} catch {}
|
|
579
|
-
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 });
|
|
580
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
|
+
};
|
|
581
642
|
|
|
582
643
|
/**
|
|
583
644
|
* Reads each MQTT packet's fixed header (a type byte, then its length in 1 to 4 bytes of 7 bits,
|
|
@@ -702,12 +763,26 @@ export class Carrier {
|
|
|
702
763
|
// Before anything reads the store: a recovery made by another process (sigelo-agent recover)
|
|
703
764
|
// is seen at once. The store's marks are written first; the state keeps the events.
|
|
704
765
|
if (this.#markRecovered(ctx)) saveState(this.statePath, ctx.st);
|
|
766
|
+
if (this.#lapse(ctx)) saveState(this.statePath, ctx.st);
|
|
705
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);
|
|
706
770
|
if (write) { saveState(this.statePath, ctx.st); ctx.store.commit(); }
|
|
707
771
|
return out;
|
|
708
772
|
});
|
|
709
773
|
}
|
|
710
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
|
+
}
|
|
711
786
|
#read(fn) { return this.#with(false, fn); }
|
|
712
787
|
|
|
713
788
|
// This agent recovered after it last told a contact of its keys (`announced`: a DID at or before
|
|
@@ -855,7 +930,7 @@ export class Carrier {
|
|
|
855
930
|
if (c.revoked) fail('revoked', `${c.did} was revoked by this owner`);
|
|
856
931
|
} else {
|
|
857
932
|
const hits = this.#liveContacts(store).filter((x) => x.name === to);
|
|
858
|
-
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`);
|
|
859
934
|
if (hits.length > 1) fail('name', `${hits.length} contacts are named ${JSON.stringify(to)}: use the DID`);
|
|
860
935
|
c = hits[0];
|
|
861
936
|
}
|
|
@@ -1190,7 +1265,7 @@ export class Carrier {
|
|
|
1190
1265
|
st.peers[c.did] = { session: dumpSession(s), announced: me.current_did, known: me.current_did, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: now };
|
|
1191
1266
|
this.#queue(st, { ...entry, bytes: frame });
|
|
1192
1267
|
this.#routes = new Map();
|
|
1193
|
-
return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed })];
|
|
1268
|
+
return [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) })];
|
|
1194
1269
|
}
|
|
1195
1270
|
|
|
1196
1271
|
// Alice: her reply will never reach the answerer (refused, too large, or its code expired while
|
|
@@ -1255,13 +1330,13 @@ export class Carrier {
|
|
|
1255
1330
|
const answered = waiting.find(([x]) => x === id)[1], held = answered.as ?? null;
|
|
1256
1331
|
const c = renamed(store, store.lookup(res.did), answered);
|
|
1257
1332
|
const s = session({ me: { did: me.did, current_did: me.current_did, secret: me.secret }, peer: c, K: hexToBytes(res.pair_key) });
|
|
1258
|
-
const events = [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed })];
|
|
1333
|
+
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) })];
|
|
1259
1334
|
try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
|
|
1260
1335
|
if (!(e instanceof MsgError)) throw e;
|
|
1261
1336
|
events.push({ type: 'dropped', check: e.check, detail: `the reply's prekeys: ${e.message}` });
|
|
1262
1337
|
}
|
|
1263
1338
|
st.peers[c.did] = { session: dumpSession(s), announced: held, known: held, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: 0 };
|
|
1264
|
-
for (const [x] of waiting) this.#handshakes.set(x, { contact: { name: c.name, did: c.did, current_did: c.current_did } });
|
|
1339
|
+
for (const [x] of waiting) this.#handshakes.set(x, { contact: { name: c.name, did: c.did, current_did: c.current_did, fingerprint: wordsOf(res.pair_key) } });
|
|
1265
1340
|
this.#routes = new Map();
|
|
1266
1341
|
return events;
|
|
1267
1342
|
}
|
|
@@ -1584,11 +1659,11 @@ export class Carrier {
|
|
|
1584
1659
|
const { me, proven } = this.#read(({ me, st }) => ({ me, proven: st.relays[relay]?.proven === true }));
|
|
1585
1660
|
const powMax = relay === this.relay ? POW_MAX : POW_MAX_OTHER;
|
|
1586
1661
|
const r = await http(`${ep.http}/challenge?did=${encodeURIComponent(me.current_did)}`);
|
|
1587
|
-
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);
|
|
1588
1663
|
// Any other status is no answer about this agent (nginx says 502 while the relay restarts):
|
|
1589
1664
|
// `connect`, retried. `challenge`, which no retry fixes, is a 200 that is not this relay's
|
|
1590
1665
|
// challenge for this agent.
|
|
1591
|
-
if (r.status !== 200)
|
|
1666
|
+
if (r.status !== 200) refuse('connect', `${relay}: ${statusWhy(r, 'GET /challenge')}`, r);
|
|
1592
1667
|
const ch = r.body?.challenge;
|
|
1593
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) {
|
|
1594
1669
|
fail('challenge', `GET /challenge did not answer a login body {v: "${LOGIN_V}", typ: "${TYP_LOGIN}", did, relay, nonce}`);
|
|
@@ -1778,7 +1853,10 @@ export class Carrier {
|
|
|
1778
1853
|
|
|
1779
1854
|
// ---- the verbs
|
|
1780
1855
|
|
|
1781
|
-
|
|
1856
|
+
// short: the long code is parked at the relay (POST /park, relay/park.mjs) under a short code
|
|
1857
|
+
// (short.mjs) for SHORT_TTL seconds, one fetch; refused, the invite is withdrawn as when its topic
|
|
1858
|
+
// is. A login of its own: the relay checks that the parked code is this agent's.
|
|
1859
|
+
async invite({ name, ttl, short = false } = {}) {
|
|
1782
1860
|
const code = this.#locked(({ now, me, store }) => {
|
|
1783
1861
|
const code = makeInvite({ did: me.current_did, relay: this.relay, now, ...(ttl !== undefined && { ttl }) });
|
|
1784
1862
|
store.addInvite(code, name ?? `invite-${code.nonce.slice(1, 9)}`, now);
|
|
@@ -1792,16 +1870,54 @@ export class Carrier {
|
|
|
1792
1870
|
const r = this.#refusedTopics.get(t);
|
|
1793
1871
|
fail(r?.code ?? 'subscribe', `the relay did not let this agent claim the invite's topic${r ? ` (${relaySays(r.detail)})` : ''}`);
|
|
1794
1872
|
}
|
|
1873
|
+
if (!short) return { code: code.text, did: code.did, relay: code.relay, exp: code.exp };
|
|
1874
|
+
const s = makeShort(), exp = Math.min(checkNow(this.clock()) + SHORT_TTL, code.exp), ep = endpointOf(code.relay, this.endpoints);
|
|
1875
|
+
const creds = await this.#credentials(code.relay, ep);
|
|
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 }) });
|
|
1877
|
+
const check = typeof r.body?.check === 'string' ? r.body.check : null;
|
|
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 };
|
|
1795
1888
|
} catch (e) {
|
|
1796
1889
|
try { this.#locked(({ store }) => store.cancelInvite(code.nonce)); } catch {}
|
|
1797
1890
|
throw e;
|
|
1798
1891
|
}
|
|
1799
|
-
return { code: code.text, did: code.did, relay: code.relay, exp: code.exp };
|
|
1800
1892
|
}
|
|
1801
1893
|
|
|
1802
|
-
|
|
1894
|
+
// The long code parked under a short one, at this agent's own relay (a short code names none):
|
|
1895
|
+
// GET /park/<code hash>, which the relay answers once. Whatever it answers is a code to parse
|
|
1896
|
+
// like any other (accept); the four words show whether the pairing is the inviter's.
|
|
1897
|
+
async unpark(text) {
|
|
1898
|
+
const shown = formatShort(normaliseShort(text)), ep = endpointOf(this.relay, this.endpoints);
|
|
1899
|
+
const r = await http(`${ep.http}/park/${codeHash(text)}`);
|
|
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);
|
|
1901
|
+
if (r.status === 404 && r.body?.check === 'park_unknown') {
|
|
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);
|
|
1903
|
+
}
|
|
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);
|
|
1907
|
+
return r.body.invite;
|
|
1908
|
+
}
|
|
1909
|
+
|
|
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 } = {}) {
|
|
1803
1919
|
const { code, id, entry } = this.#locked(({ now, me, store, st }) => {
|
|
1804
|
-
const code =
|
|
1920
|
+
const code = readCode(text, now, how);
|
|
1805
1921
|
// This agent's own relay, and those its operator configured, are the operator's choice.
|
|
1806
1922
|
if (code.relay !== this.relay && !Object.hasOwn(this.endpoints ?? {}, code.relay) && !publicRelay(code.relay)) {
|
|
1807
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`);
|
|
@@ -1844,13 +1960,20 @@ export class Carrier {
|
|
|
1844
1960
|
return 'withdrawn';
|
|
1845
1961
|
});
|
|
1846
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];
|
|
1847
|
-
|
|
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;
|
|
1848
1966
|
}
|
|
1849
1967
|
const h = this.#handshakes.get(id), sent = this.#results.get(entry);
|
|
1850
1968
|
this.#handshakes.delete(id); this.#results.delete(entry);
|
|
1851
1969
|
if (h?.check) fail(h.check, h.detail);
|
|
1852
1970
|
if (h) return { status: 'connected', contact: h.contact };
|
|
1853
|
-
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
|
+
}
|
|
1854
1977
|
if (sent?.code) drop(sent.code, `the relay refused the answer (${relaySays(sent.detail)})`);
|
|
1855
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' };
|
|
1856
1979
|
return { status: 'waiting', did: code.did, relay: code.relay, detail: 'answer delivered; the pairing completes when the inviter\'s agent next connects' };
|
|
@@ -1861,9 +1984,11 @@ export class Carrier {
|
|
|
1861
1984
|
const s = store.load().s;
|
|
1862
1985
|
return {
|
|
1863
1986
|
contacts: Object.values(s.contacts).map((c) => ({ name: c.name, did: c.did, current_did: c.current_did, revoked: c.revoked, relay: c.relay, queued: st.peers[c.did]?.outbox.length ?? 0,
|
|
1864
|
-
re_pair: c.re_pair ?? null })),
|
|
1987
|
+
re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key) })),
|
|
1865
1988
|
invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
|
|
1866
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 })),
|
|
1867
1992
|
};
|
|
1868
1993
|
});
|
|
1869
1994
|
}
|
|
@@ -1907,7 +2032,7 @@ export class Carrier {
|
|
|
1907
2032
|
return { ids, c };
|
|
1908
2033
|
});
|
|
1909
2034
|
try { await this.#session([c.relay]); } catch (e) {
|
|
1910
|
-
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 });
|
|
1911
2036
|
}
|
|
1912
2037
|
return ids.map((id) => {
|
|
1913
2038
|
const r = this.#results.get(id);
|
|
@@ -1926,7 +2051,7 @@ export class Carrier {
|
|
|
1926
2051
|
const inUse = this.#relaysInUse(), relays = inUse.length > 0 ? inUse : [this.relay];
|
|
1927
2052
|
try {
|
|
1928
2053
|
await this.#session(relays, wait > 0 ? { max: wait * 1000, until: () => this.#read(({ st }) => st.inbox.length > 0) } : {});
|
|
1929
|
-
} 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}`; }
|
|
1930
2055
|
return this.#locked(({ st }) => {
|
|
1931
2056
|
const out = { messages: st.inbox, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
|
|
1932
2057
|
st.inbox = []; st.events = []; st.dropped = {};
|
|
@@ -1944,7 +2069,7 @@ export class Carrier {
|
|
|
1944
2069
|
this.#routes = new Map();
|
|
1945
2070
|
// Revoked here whatever the relay says; offline: its mailboxes are given up at a later round.
|
|
1946
2071
|
let offline = null;
|
|
1947
|
-
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}`; }
|
|
1948
2073
|
const released = this.#read(({ st }) => !Object.values(st.relays[c.relay]?.claims ?? {}).some((x) => x.peer === c.did));
|
|
1949
2074
|
return { name: c.name, did: c.did, revoked: true, released, ...(offline && { offline }) };
|
|
1950
2075
|
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
{
|
|
2
|
+
"contract": "sigelo-park/0",
|
|
3
|
+
"alphabet": "0123456789ABCDEFGHJKMNPQRSTVWXYZ",
|
|
4
|
+
"rules": {
|
|
5
|
+
"code": "8 characters of the alphabet from 5 random bytes, 5 bits each, most significant first; shown as XXXX-XXXX; lives 600 s, one fetch",
|
|
6
|
+
"normalise": "drop whitespace and dashes (U+002D, U+2010 to U+2015, U+2212); uppercase; I and L → 1, O → 0; then exactly 8 characters of the alphabet, else short_code",
|
|
7
|
+
"code_hash": "hex(SHA-256(UTF-8 \"sigelo-park/0\" ‖ UTF-8 normalised code))",
|
|
8
|
+
"fingerprint": "HKDF-SHA256(16 bytes of the pair id, salt \"sigelo-fingerprint/0\", empty info, 6 bytes); the first 44 bits, 11 at a time, index the BIP-39 English list (sha256 of the list one word a line: 2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda)",
|
|
9
|
+
"rng": "rng(label) = first 5 bytes of SHA-256(UTF-8 \"sigelo-park/0 \" + label)"
|
|
10
|
+
},
|
|
11
|
+
"codes": [
|
|
12
|
+
{
|
|
13
|
+
"label": "a",
|
|
14
|
+
"rng": "7c330786cc",
|
|
15
|
+
"code": "FGSG-F1PC",
|
|
16
|
+
"normalised": "FGSGF1PC",
|
|
17
|
+
"code_hash": "629f5c50434574b583aae6fa4664a7ace329e2a0a62ef29140dcbdc21424a443"
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"label": "b",
|
|
21
|
+
"rng": "ebac845f43",
|
|
22
|
+
"code": "XEP8-8QT3",
|
|
23
|
+
"normalised": "XEP88QT3",
|
|
24
|
+
"code_hash": "0778a95c3785446e88f6df877abcc6793787a6d53825af7f01fac2d6b23da66a"
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"label": "c",
|
|
28
|
+
"rng": "29efe35974",
|
|
29
|
+
"code": "57QY-6PBM",
|
|
30
|
+
"normalised": "57QY6PBM",
|
|
31
|
+
"code_hash": "f31675864983beeadd2f46fe62891864f87071011d5a5c719208d241a027f263"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"label": "d",
|
|
35
|
+
"rng": "3b9f02b509",
|
|
36
|
+
"code": "7EFG-5D89",
|
|
37
|
+
"normalised": "7EFG5D89",
|
|
38
|
+
"code_hash": "529f4d2fe1fcacf4e51f84b6859a668dadf2dff69ff107a159e794000642af2d"
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
"label": "zeros",
|
|
42
|
+
"rng": "0000000000",
|
|
43
|
+
"code": "0000-0000",
|
|
44
|
+
"normalised": "00000000",
|
|
45
|
+
"code_hash": "e90299d03e123d1c92eb28b8e5ca42b7a719fe6b2cd25503fd94eba3a67511ee"
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"label": "ones",
|
|
49
|
+
"rng": "ffffffffff",
|
|
50
|
+
"code": "ZZZZ-ZZZZ",
|
|
51
|
+
"normalised": "ZZZZZZZZ",
|
|
52
|
+
"code_hash": "d64ebd4f29ed60b23dc016c34c92a9ad0dd43f134ae3578206d6e06894938898"
|
|
53
|
+
}
|
|
54
|
+
],
|
|
55
|
+
"normalise": [
|
|
56
|
+
{
|
|
57
|
+
"case": "as shown",
|
|
58
|
+
"input": "FGSG-F1PC",
|
|
59
|
+
"normalised": "FGSGF1PC"
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
"case": "without the dash",
|
|
63
|
+
"input": "FGSGF1PC",
|
|
64
|
+
"normalised": "FGSGF1PC"
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"case": "lowercase",
|
|
68
|
+
"input": "fgsg-f1pc",
|
|
69
|
+
"normalised": "FGSGF1PC"
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"case": "spoken in groups",
|
|
73
|
+
"input": " fg sg f1 pc ",
|
|
74
|
+
"normalised": "FGSGF1PC"
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
"case": "an en dash from a phone",
|
|
78
|
+
"input": "FGSG–F1PC",
|
|
79
|
+
"normalised": "FGSGF1PC"
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
"case": "I, i, L and l read as 1",
|
|
83
|
+
"input": "IiLl-2345",
|
|
84
|
+
"normalised": "11112345"
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
"case": "O and o read as 0",
|
|
88
|
+
"input": "Oo00-ABCD",
|
|
89
|
+
"normalised": "0000ABCD"
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
"case": "U is no digit",
|
|
93
|
+
"input": "U000-0000",
|
|
94
|
+
"error": "short_code"
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"case": "seven characters",
|
|
98
|
+
"input": "FGSG-F1P",
|
|
99
|
+
"error": "short_code"
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
"case": "nine characters",
|
|
103
|
+
"input": "FGSGF1PC0",
|
|
104
|
+
"error": "short_code"
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
"case": "a symbol",
|
|
108
|
+
"input": "K7F3_Q9ZP",
|
|
109
|
+
"error": "short_code"
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
"case": "a long code",
|
|
113
|
+
"input": "sgl122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222",
|
|
114
|
+
"error": "short_code"
|
|
115
|
+
}
|
|
116
|
+
],
|
|
117
|
+
"fingerprints": [
|
|
118
|
+
{
|
|
119
|
+
"case": "carrier-v0.json derived.pair",
|
|
120
|
+
"pair": "a2cf45bd3d6aee6d6e3f14ffd2751924",
|
|
121
|
+
"okm": "d6a99a189c6c",
|
|
122
|
+
"indices": [
|
|
123
|
+
1717,
|
|
124
|
+
614,
|
|
125
|
+
1073,
|
|
126
|
+
454
|
|
127
|
+
],
|
|
128
|
+
"words": "stove error mail decide"
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
"case": "zero pair",
|
|
132
|
+
"pair": "00000000000000000000000000000000",
|
|
133
|
+
"okm": "06cbb8ea02e1",
|
|
134
|
+
"indices": [
|
|
135
|
+
54,
|
|
136
|
+
750,
|
|
137
|
+
468,
|
|
138
|
+
46
|
|
139
|
+
],
|
|
140
|
+
"words": "almost fruit dentist alarm"
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
"case": "ones pair",
|
|
144
|
+
"pair": "ffffffffffffffffffffffffffffffff",
|
|
145
|
+
"okm": "a11ec15d70ec",
|
|
146
|
+
"indices": [
|
|
147
|
+
1288,
|
|
148
|
+
1968,
|
|
149
|
+
698,
|
|
150
|
+
1806
|
|
151
|
+
],
|
|
152
|
+
"words": "patient voyage firm tide"
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
"case": "pair of rng(\"pair\")",
|
|
156
|
+
"pair": "41068cf691662c20931f820952ac3ddf",
|
|
157
|
+
"okm": "3f11eb6818b3",
|
|
158
|
+
"indices": [
|
|
159
|
+
504,
|
|
160
|
+
1146,
|
|
161
|
+
1744,
|
|
162
|
+
395
|
|
163
|
+
],
|
|
164
|
+
"words": "disease monster sure cousin"
|
|
165
|
+
}
|
|
166
|
+
]
|
|
167
|
+
}
|
package/gen-short.mjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Regenerates fixtures/short-code-v0.json, byte for byte: contract sigelo-park/0 (short.mjs header).
|
|
3
|
+
// node contact/gen-short.mjs write the file
|
|
4
|
+
// node contact/gen-short.mjs --check exit 1 if the committed file differs
|
|
5
|
+
// Independent of short.mjs on purpose: base32, normalisation, hashes and words are worked out here
|
|
6
|
+
// with node:crypto and string handling of their own, so the fixture checks short.mjs (test-short.mjs)
|
|
7
|
+
// instead of echoing it. The word list is read from bip39-english.mjs (data only; its hash is
|
|
8
|
+
// checked here). Random inputs: rng(label) = SHA-256("sigelo-park/0 " + label), first 5 bytes.
|
|
9
|
+
// Output: JSON.stringify(out, null, 2) + "\n".
|
|
10
|
+
import { createHash, hkdfSync } from 'node:crypto';
|
|
11
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { dirname, join } from 'node:path';
|
|
13
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
14
|
+
import { BIP39_SHA256, WORDS } from './bip39-english.mjs';
|
|
15
|
+
|
|
16
|
+
const V = 'sigelo-park/0', LABEL = 'sigelo-fingerprint/0';
|
|
17
|
+
const OUT = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'short-code-v0.json');
|
|
18
|
+
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
19
|
+
const sha = (b) => createHash('sha256').update(b).digest();
|
|
20
|
+
if (sha(WORDS.join('\n') + '\n').toString('hex') !== BIP39_SHA256 || WORDS.length !== 2048) throw new Error('bip39-english.mjs is not the BIP-39 English list');
|
|
21
|
+
|
|
22
|
+
// 40 bits → 8 digits, as a binary string cut in fives.
|
|
23
|
+
const encode = (bytes) => [...bytes].map((b) => b.toString(2).padStart(8, '0')).join('').match(/.{5}/g).map((s) => CROCKFORD[parseInt(s, 2)]).join('');
|
|
24
|
+
const rng = (label) => sha(`${V} ${label}`).subarray(0, 5);
|
|
25
|
+
const hashOf = (norm) => sha(Buffer.concat([Buffer.from(V, 'utf8'), Buffer.from(norm, 'utf8')])).toString('hex');
|
|
26
|
+
|
|
27
|
+
const made = ['a', 'b', 'c', 'd'].map((l) => {
|
|
28
|
+
const bytes = rng(l), code = encode(bytes);
|
|
29
|
+
return { label: l, rng: bytes.toString('hex'), code: `${code.slice(0, 4)}-${code.slice(4)}`, normalised: code, code_hash: hashOf(code) };
|
|
30
|
+
});
|
|
31
|
+
// The edges of the alphabet: all zero bits, all one bits.
|
|
32
|
+
made.push({ label: 'zeros', rng: '0000000000', code: '0000-0000', normalised: '00000000', code_hash: hashOf('00000000') });
|
|
33
|
+
made.push({ label: 'ones', rng: 'ffffffffff', code: 'ZZZZ-ZZZZ', normalised: 'ZZZZZZZZ', code_hash: hashOf('ZZZZZZZZ') });
|
|
34
|
+
|
|
35
|
+
const K = made[0].normalised, k = K.toLowerCase();
|
|
36
|
+
const normalise = [
|
|
37
|
+
{ case: 'as shown', input: `${K.slice(0, 4)}-${K.slice(4)}`, normalised: K },
|
|
38
|
+
{ case: 'without the dash', input: K, normalised: K },
|
|
39
|
+
{ case: 'lowercase', input: `${k.slice(0, 4)}-${k.slice(4)}`, normalised: K },
|
|
40
|
+
{ case: 'spoken in groups', input: ` ${k.slice(0, 2)} ${k.slice(2, 4)} ${k.slice(4, 6)} ${k.slice(6)} `, normalised: K },
|
|
41
|
+
{ case: 'an en dash from a phone', input: `${K.slice(0, 4)}–${K.slice(4)}`, normalised: K },
|
|
42
|
+
{ case: 'I, i, L and l read as 1', input: 'IiLl-2345', normalised: '11112345' },
|
|
43
|
+
{ case: 'O and o read as 0', input: 'Oo00-ABCD', normalised: '0000ABCD' },
|
|
44
|
+
{ case: 'U is no digit', input: 'U000-0000', error: 'short_code' },
|
|
45
|
+
{ case: 'seven characters', input: `${K.slice(0, 4)}-${K.slice(4, 7)}`, error: 'short_code' },
|
|
46
|
+
{ case: 'nine characters', input: `${K}0`, error: 'short_code' },
|
|
47
|
+
{ case: 'a symbol', input: 'K7F3_Q9ZP', error: 'short_code' },
|
|
48
|
+
{ case: 'a long code', input: 'sgl1' + '2'.repeat(122), error: 'short_code' },
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
// The words: HKDF-SHA256(pair, salt LABEL, empty info, 6 bytes), first 44 bits, 11 at a time.
|
|
52
|
+
function words(pairHex) {
|
|
53
|
+
const okm = Buffer.from(hkdfSync('sha256', Buffer.from(pairHex, 'hex'), Buffer.from(LABEL, 'utf8'), Buffer.alloc(0), 6));
|
|
54
|
+
const bits = [...okm].map((b) => b.toString(2).padStart(8, '0')).join('').slice(0, 44);
|
|
55
|
+
const indices = bits.match(/.{11}/g).map((s) => parseInt(s, 2));
|
|
56
|
+
return { okm: okm.toString('hex'), indices, words: indices.map((i) => WORDS[i]).join(' ') };
|
|
57
|
+
}
|
|
58
|
+
const carrier = JSON.parse(readFileSync(join(dirname(OUT), 'carrier-v0.json'), 'utf8')).derived.pair.hex;
|
|
59
|
+
const fingerprints = [
|
|
60
|
+
{ case: 'carrier-v0.json derived.pair', pair: carrier, ...words(carrier) },
|
|
61
|
+
{ case: 'zero pair', pair: '0'.repeat(32), ...words('0'.repeat(32)) },
|
|
62
|
+
{ case: 'ones pair', pair: 'f'.repeat(32), ...words('f'.repeat(32)) },
|
|
63
|
+
{ case: 'pair of rng("pair")', pair: sha(`${V} pair`).subarray(0, 16).toString('hex'), ...words(sha(`${V} pair`).subarray(0, 16).toString('hex')) },
|
|
64
|
+
];
|
|
65
|
+
|
|
66
|
+
export function build() {
|
|
67
|
+
const out = {
|
|
68
|
+
contract: V,
|
|
69
|
+
alphabet: CROCKFORD,
|
|
70
|
+
rules: {
|
|
71
|
+
code: '8 characters of the alphabet from 5 random bytes, 5 bits each, most significant first; shown as XXXX-XXXX; lives 600 s, one fetch',
|
|
72
|
+
normalise: 'drop whitespace and dashes (U+002D, U+2010 to U+2015, U+2212); uppercase; I and L → 1, O → 0; then exactly 8 characters of the alphabet, else short_code',
|
|
73
|
+
code_hash: 'hex(SHA-256(UTF-8 "sigelo-park/0" ‖ UTF-8 normalised code))',
|
|
74
|
+
fingerprint: 'HKDF-SHA256(16 bytes of the pair id, salt "sigelo-fingerprint/0", empty info, 6 bytes); the first 44 bits, 11 at a time, index the BIP-39 English list (sha256 of the list one word a line: ' + BIP39_SHA256 + ')',
|
|
75
|
+
rng: 'rng(label) = first 5 bytes of SHA-256(UTF-8 "sigelo-park/0 " + label)',
|
|
76
|
+
},
|
|
77
|
+
codes: made,
|
|
78
|
+
normalise,
|
|
79
|
+
fingerprints,
|
|
80
|
+
};
|
|
81
|
+
return JSON.stringify(out, null, 2) + '\n';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
85
|
+
const text = build();
|
|
86
|
+
if (process.argv.includes('--check')) {
|
|
87
|
+
let cur = '';
|
|
88
|
+
try { cur = readFileSync(OUT, 'utf8'); } catch {}
|
|
89
|
+
if (cur !== text) { console.error('short-code-v0.json differs from the seeds: run node contact/gen-short.mjs'); process.exit(1); }
|
|
90
|
+
console.log('short-code-v0.json reproduces byte for byte');
|
|
91
|
+
} else { writeFileSync(OUT, text); console.log(`wrote ${OUT.split('/').slice(-2).join('/')} (${text.length} bytes)`); }
|
|
92
|
+
}
|