sigelo-contact 0.1.4 → 0.1.5

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 CHANGED
@@ -1,13 +1,13 @@
1
1
  <!-- SPDX-License-Identifier: MIT -->
2
2
  # sigelo-contact
3
3
 
4
- Two agents swap a one-line code, then send each other end-to-end encrypted
4
+ Two agents swap a short code, then send each other end-to-end encrypted
5
5
  messages through a relay that holds them while one is offline and cannot read them. Each checks
6
6
  the other's sigelo chain offline; a key rotation keeps the contact. MIT; the relay,
7
7
  [sigelo-relay](https://github.com/csigelo/sigelo-relay), is AGPL-3.0.
8
8
 
9
9
  ```sh
10
- sigelo-agent invite --name bob # alice: one-time code, 24 hours
10
+ sigelo-agent invite --name bob # alice: K7F3-Q9ZP, once, 10 minutes
11
11
  sigelo-agent accept <code> --name alice # bob: checks alice offline, pairs
12
12
  sigelo-agent send bob "hello" # sent, or queued until bob's agent connects
13
13
  seq 3 | sigelo-agent send bob - --lines # one message a line, one login
@@ -0,0 +1,283 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // The BIP-39 English wordlist, 2048 words in their order (the order IS the encoding: never sort).
3
+ // Vendored from bitcoin/bips bip-0039/english.txt as trezor/python-mnemonic ships it, under that
4
+ // project's licence below. SHA-256 of the list one word a line, each line ending in "\n":
5
+ // BIP39_SHA256 (test-short.mjs checks it). Used for the four words of a pairing (short.mjs).
6
+ //
7
+ // The MIT License (MIT)
8
+ //
9
+ // Copyright (c) 2013 Pavol Rusnak
10
+ //
11
+ // Permission is hereby granted, free of charge, to any person obtaining a copy of this software
12
+ // and associated documentation files (the "Software"), to deal in the Software without
13
+ // restriction, including without limitation the rights to use, copy, modify, merge, publish,
14
+ // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
15
+ // Software is furnished to do so, subject to the following conditions:
16
+ //
17
+ // The above copyright notice and this permission notice shall be included in all copies or
18
+ // substantial portions of the Software.
19
+ //
20
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
21
+ // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22
+ // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
23
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25
+ export const BIP39_SHA256 = '2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda';
26
+ export const WORDS = Object.freeze(`
27
+ abandon ability able about above absent absorb abstract
28
+ absurd abuse access accident account accuse achieve acid
29
+ acoustic acquire across act action actor actress actual
30
+ adapt add addict address adjust admit adult advance
31
+ advice aerobic affair afford afraid again age agent
32
+ agree ahead aim air airport aisle alarm album
33
+ alcohol alert alien all alley allow almost alone
34
+ alpha already also alter always amateur amazing among
35
+ amount amused analyst anchor ancient anger angle angry
36
+ animal ankle announce annual another answer antenna antique
37
+ anxiety any apart apology appear apple approve april
38
+ arch arctic area arena argue arm armed armor
39
+ army around arrange arrest arrive arrow art artefact
40
+ artist artwork ask aspect assault asset assist assume
41
+ asthma athlete atom attack attend attitude attract auction
42
+ audit august aunt author auto autumn average avocado
43
+ avoid awake aware away awesome awful awkward axis
44
+ baby bachelor bacon badge bag balance balcony ball
45
+ bamboo banana banner bar barely bargain barrel base
46
+ basic basket battle beach bean beauty because become
47
+ beef before begin behave behind believe below belt
48
+ bench benefit best betray better between beyond bicycle
49
+ bid bike bind biology bird birth bitter black
50
+ blade blame blanket blast bleak bless blind blood
51
+ blossom blouse blue blur blush board boat body
52
+ boil bomb bone bonus book boost border boring
53
+ borrow boss bottom bounce box boy bracket brain
54
+ brand brass brave bread breeze brick bridge brief
55
+ bright bring brisk broccoli broken bronze broom brother
56
+ brown brush bubble buddy budget buffalo build bulb
57
+ bulk bullet bundle bunker burden burger burst bus
58
+ business busy butter buyer buzz cabbage cabin cable
59
+ cactus cage cake call calm camera camp can
60
+ canal cancel candy cannon canoe canvas canyon capable
61
+ capital captain car carbon card cargo carpet carry
62
+ cart case cash casino castle casual cat catalog
63
+ catch category cattle caught cause caution cave ceiling
64
+ celery cement census century cereal certain chair chalk
65
+ champion change chaos chapter charge chase chat cheap
66
+ check cheese chef cherry chest chicken chief child
67
+ chimney choice choose chronic chuckle chunk churn cigar
68
+ cinnamon circle citizen city civil claim clap clarify
69
+ claw clay clean clerk clever click client cliff
70
+ climb clinic clip clock clog close cloth cloud
71
+ clown club clump cluster clutch coach coast coconut
72
+ code coffee coil coin collect color column combine
73
+ come comfort comic common company concert conduct confirm
74
+ congress connect consider control convince cook cool copper
75
+ copy coral core corn correct cost cotton couch
76
+ country couple course cousin cover coyote crack cradle
77
+ craft cram crane crash crater crawl crazy cream
78
+ credit creek crew cricket crime crisp critic crop
79
+ cross crouch crowd crucial cruel cruise crumble crunch
80
+ crush cry crystal cube culture cup cupboard curious
81
+ current curtain curve cushion custom cute cycle dad
82
+ damage damp dance danger daring dash daughter dawn
83
+ day deal debate debris decade december decide decline
84
+ decorate decrease deer defense define defy degree delay
85
+ deliver demand demise denial dentist deny depart depend
86
+ deposit depth deputy derive describe desert design desk
87
+ despair destroy detail detect develop device devote diagram
88
+ dial diamond diary dice diesel diet differ digital
89
+ dignity dilemma dinner dinosaur direct dirt disagree discover
90
+ disease dish dismiss disorder display distance divert divide
91
+ divorce dizzy doctor document dog doll dolphin domain
92
+ donate donkey donor door dose double dove draft
93
+ dragon drama drastic draw dream dress drift drill
94
+ drink drip drive drop drum dry duck dumb
95
+ dune during dust dutch duty dwarf dynamic eager
96
+ eagle early earn earth easily east easy echo
97
+ ecology economy edge edit educate effort egg eight
98
+ either elbow elder electric elegant element elephant elevator
99
+ elite else embark embody embrace emerge emotion employ
100
+ empower empty enable enact end endless endorse enemy
101
+ energy enforce engage engine enhance enjoy enlist enough
102
+ enrich enroll ensure enter entire entry envelope episode
103
+ equal equip era erase erode erosion error erupt
104
+ escape essay essence estate eternal ethics evidence evil
105
+ evoke evolve exact example excess exchange excite exclude
106
+ excuse execute exercise exhaust exhibit exile exist exit
107
+ exotic expand expect expire explain expose express extend
108
+ extra eye eyebrow fabric face faculty fade faint
109
+ faith fall false fame family famous fan fancy
110
+ fantasy farm fashion fat fatal father fatigue fault
111
+ favorite feature february federal fee feed feel female
112
+ fence festival fetch fever few fiber fiction field
113
+ figure file film filter final find fine finger
114
+ finish fire firm first fiscal fish fit fitness
115
+ fix flag flame flash flat flavor flee flight
116
+ flip float flock floor flower fluid flush fly
117
+ foam focus fog foil fold follow food foot
118
+ force forest forget fork fortune forum forward fossil
119
+ foster found fox fragile frame frequent fresh friend
120
+ fringe frog front frost frown frozen fruit fuel
121
+ fun funny furnace fury future gadget gain galaxy
122
+ gallery game gap garage garbage garden garlic garment
123
+ gas gasp gate gather gauge gaze general genius
124
+ genre gentle genuine gesture ghost giant gift giggle
125
+ ginger giraffe girl give glad glance glare glass
126
+ glide glimpse globe gloom glory glove glow glue
127
+ goat goddess gold good goose gorilla gospel gossip
128
+ govern gown grab grace grain grant grape grass
129
+ gravity great green grid grief grit grocery group
130
+ grow grunt guard guess guide guilt guitar gun
131
+ gym habit hair half hammer hamster hand happy
132
+ harbor hard harsh harvest hat have hawk hazard
133
+ head health heart heavy hedgehog height hello helmet
134
+ help hen hero hidden high hill hint hip
135
+ hire history hobby hockey hold hole holiday hollow
136
+ home honey hood hope horn horror horse hospital
137
+ host hotel hour hover hub huge human humble
138
+ humor hundred hungry hunt hurdle hurry hurt husband
139
+ hybrid ice icon idea identify idle ignore ill
140
+ illegal illness image imitate immense immune impact impose
141
+ improve impulse inch include income increase index indicate
142
+ indoor industry infant inflict inform inhale inherit initial
143
+ inject injury inmate inner innocent input inquiry insane
144
+ insect inside inspire install intact interest into invest
145
+ invite involve iron island isolate issue item ivory
146
+ jacket jaguar jar jazz jealous jeans jelly jewel
147
+ job join joke journey joy judge juice jump
148
+ jungle junior junk just kangaroo keen keep ketchup
149
+ key kick kid kidney kind kingdom kiss kit
150
+ kitchen kite kitten kiwi knee knife knock know
151
+ lab label labor ladder lady lake lamp language
152
+ laptop large later latin laugh laundry lava law
153
+ lawn lawsuit layer lazy leader leaf learn leave
154
+ lecture left leg legal legend leisure lemon lend
155
+ length lens leopard lesson letter level liar liberty
156
+ library license life lift light like limb limit
157
+ link lion liquid list little live lizard load
158
+ loan lobster local lock logic lonely long loop
159
+ lottery loud lounge love loyal lucky luggage lumber
160
+ lunar lunch luxury lyrics machine mad magic magnet
161
+ maid mail main major make mammal man manage
162
+ mandate mango mansion manual maple marble march margin
163
+ marine market marriage mask mass master match material
164
+ math matrix matter maximum maze meadow mean measure
165
+ meat mechanic medal media melody melt member memory
166
+ mention menu mercy merge merit merry mesh message
167
+ metal method middle midnight milk million mimic mind
168
+ minimum minor minute miracle mirror misery miss mistake
169
+ mix mixed mixture mobile model modify mom moment
170
+ monitor monkey monster month moon moral more morning
171
+ mosquito mother motion motor mountain mouse move movie
172
+ much muffin mule multiply muscle museum mushroom music
173
+ must mutual myself mystery myth naive name napkin
174
+ narrow nasty nation nature near neck need negative
175
+ neglect neither nephew nerve nest net network neutral
176
+ never news next nice night noble noise nominee
177
+ noodle normal north nose notable note nothing notice
178
+ novel now nuclear number nurse nut oak obey
179
+ object oblige obscure observe obtain obvious occur ocean
180
+ october odor off offer office often oil okay
181
+ old olive olympic omit once one onion online
182
+ only open opera opinion oppose option orange orbit
183
+ orchard order ordinary organ orient original orphan ostrich
184
+ other outdoor outer output outside oval oven over
185
+ own owner oxygen oyster ozone pact paddle page
186
+ pair palace palm panda panel panic panther paper
187
+ parade parent park parrot party pass patch path
188
+ patient patrol pattern pause pave payment peace peanut
189
+ pear peasant pelican pen penalty pencil people pepper
190
+ perfect permit person pet phone photo phrase physical
191
+ piano picnic picture piece pig pigeon pill pilot
192
+ pink pioneer pipe pistol pitch pizza place planet
193
+ plastic plate play please pledge pluck plug plunge
194
+ poem poet point polar pole police pond pony
195
+ pool popular portion position possible post potato pottery
196
+ poverty powder power practice praise predict prefer prepare
197
+ present pretty prevent price pride primary print priority
198
+ prison private prize problem process produce profit program
199
+ project promote proof property prosper protect proud provide
200
+ public pudding pull pulp pulse pumpkin punch pupil
201
+ puppy purchase purity purpose purse push put puzzle
202
+ pyramid quality quantum quarter question quick quit quiz
203
+ quote rabbit raccoon race rack radar radio rail
204
+ rain raise rally ramp ranch random range rapid
205
+ rare rate rather raven raw razor ready real
206
+ reason rebel rebuild recall receive recipe record recycle
207
+ reduce reflect reform refuse region regret regular reject
208
+ relax release relief rely remain remember remind remove
209
+ render renew rent reopen repair repeat replace report
210
+ require rescue resemble resist resource response result retire
211
+ retreat return reunion reveal review reward rhythm rib
212
+ ribbon rice rich ride ridge rifle right rigid
213
+ ring riot ripple risk ritual rival river road
214
+ roast robot robust rocket romance roof rookie room
215
+ rose rotate rough round route royal rubber rude
216
+ rug rule run runway rural sad saddle sadness
217
+ safe sail salad salmon salon salt salute same
218
+ sample sand satisfy satoshi sauce sausage save say
219
+ scale scan scare scatter scene scheme school science
220
+ scissors scorpion scout scrap screen script scrub sea
221
+ search season seat second secret section security seed
222
+ seek segment select sell seminar senior sense sentence
223
+ series service session settle setup seven shadow shaft
224
+ shallow share shed shell sheriff shield shift shine
225
+ ship shiver shock shoe shoot shop short shoulder
226
+ shove shrimp shrug shuffle shy sibling sick side
227
+ siege sight sign silent silk silly silver similar
228
+ simple since sing siren sister situate six size
229
+ skate sketch ski skill skin skirt skull slab
230
+ slam sleep slender slice slide slight slim slogan
231
+ slot slow slush small smart smile smoke smooth
232
+ snack snake snap sniff snow soap soccer social
233
+ sock soda soft solar soldier solid solution solve
234
+ someone song soon sorry sort soul sound soup
235
+ source south space spare spatial spawn speak special
236
+ speed spell spend sphere spice spider spike spin
237
+ spirit split spoil sponsor spoon sport spot spray
238
+ spread spring spy square squeeze squirrel stable stadium
239
+ staff stage stairs stamp stand start state stay
240
+ steak steel stem step stereo stick still sting
241
+ stock stomach stone stool story stove strategy street
242
+ strike strong struggle student stuff stumble style subject
243
+ submit subway success such sudden suffer sugar suggest
244
+ suit summer sun sunny sunset super supply supreme
245
+ sure surface surge surprise surround survey suspect sustain
246
+ swallow swamp swap swarm swear sweet swift swim
247
+ swing switch sword symbol symptom syrup system table
248
+ tackle tag tail talent talk tank tape target
249
+ task taste tattoo taxi teach team tell ten
250
+ tenant tennis tent term test text thank that
251
+ theme then theory there they thing this thought
252
+ three thrive throw thumb thunder ticket tide tiger
253
+ tilt timber time tiny tip tired tissue title
254
+ toast tobacco today toddler toe together toilet token
255
+ tomato tomorrow tone tongue tonight tool tooth top
256
+ topic topple torch tornado tortoise toss total tourist
257
+ toward tower town toy track trade traffic tragic
258
+ train transfer trap trash travel tray treat tree
259
+ trend trial tribe trick trigger trim trip trophy
260
+ trouble truck true truly trumpet trust truth try
261
+ tube tuition tumble tuna tunnel turkey turn turtle
262
+ twelve twenty twice twin twist two type typical
263
+ ugly umbrella unable unaware uncle uncover under undo
264
+ unfair unfold unhappy uniform unique unit universe unknown
265
+ unlock until unusual unveil update upgrade uphold upon
266
+ upper upset urban urge usage use used useful
267
+ useless usual utility vacant vacuum vague valid valley
268
+ valve van vanish vapor various vast vault vehicle
269
+ velvet vendor venture venue verb verify version very
270
+ vessel veteran viable vibrant vicious victory video view
271
+ village vintage violin virtual virus visa visit visual
272
+ vital vivid vocal voice void volcano volume vote
273
+ voyage wage wagon wait walk wall walnut want
274
+ warfare warm warrior wash wasp waste water wave
275
+ way wealth weapon wear weasel weather web wedding
276
+ weekend weird welcome west wet whale what wheat
277
+ wheel when where whip whisper wide width wife
278
+ wild will win window wine wing wink winner
279
+ winter wire wisdom wise wish witness wolf woman
280
+ wonder wood wool word work world worry worth
281
+ wrap wreck wrestle wrist write wrong yard year
282
+ yellow you young youth zebra zero zone zoo
283
+ `.trim().split(/\s+/));
package/carrier.mjs CHANGED
@@ -4,9 +4,11 @@
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 }) → { code, did, relay, exp } the answer topic is claimed first
8
- // await c.accept(code, { name, wait }) → { status: 'connected' | 'waiting' | 'pending', … }
9
- // c.contacts() → { contacts, invites, answers }
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
+ // c.contacts() → { contacts, invites, answers } each contact with its four words (fingerprint)
10
12
  // await c.send(to, content, { label }) → { status: 'sent' | 'queued', … }, or throws the relay's code
11
13
  // await c.sendAll(to, contents, { label }) → one result each ('refused' with its code), one login
12
14
  // await c.inbox({ wait }) → { messages, events, dropped, offline? }: all are taken (messages: those kept)
@@ -149,6 +151,7 @@ import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, inviteKeys,
149
151
  import { MsgError, checkNow, fail, hex, isoWeek, pairId, topic } from './kdf.mjs';
150
152
  import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
151
153
  import { Contacts } from './store.mjs';
154
+ import { SHORT_TTL, codeHash, fingerprint, formatShort, isShort, makeShort } from './short.mjs';
152
155
 
153
156
  export const V = 'sigelo-carrier/0';
154
157
  export const DEFAULT_RELAY = 'relay.sigelo.ai', MQTT_PORT = 8883, NOTICE = '$sigelo/notice';
@@ -256,6 +259,10 @@ const b64 = (b) => Buffer.from(b).toString('base64');
256
259
  const unb64 = (s) => new Uint8Array(Buffer.from(s, 'base64'));
257
260
  const randomId = () => hex(randomBytes(8));
258
261
  const clientIdOf = (original) => 's' + createHash('sha256').update(original, 'utf8').digest('hex').slice(0, 24);
262
+ // The four words of a pairing (short.mjs), from its pairing key as the store holds it (hex), or null.
263
+ const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
264
+ // The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
265
+ const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_CHECKS]);
259
266
 
260
267
  // ---------------------------------------------------------------- configuration
261
268
 
@@ -1190,7 +1197,7 @@ export class Carrier {
1190
1197
  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
1198
  this.#queue(st, { ...entry, bytes: frame });
1192
1199
  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 })];
1200
+ 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
1201
  }
1195
1202
 
1196
1203
  // Alice: her reply will never reach the answerer (refused, too large, or its code expired while
@@ -1255,13 +1262,13 @@ export class Carrier {
1255
1262
  const answered = waiting.find(([x]) => x === id)[1], held = answered.as ?? null;
1256
1263
  const c = renamed(store, store.lookup(res.did), answered);
1257
1264
  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 })];
1265
+ 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
1266
  try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
1260
1267
  if (!(e instanceof MsgError)) throw e;
1261
1268
  events.push({ type: 'dropped', check: e.check, detail: `the reply's prekeys: ${e.message}` });
1262
1269
  }
1263
1270
  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 } });
1271
+ 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
1272
  this.#routes = new Map();
1266
1273
  return events;
1267
1274
  }
@@ -1778,7 +1785,10 @@ export class Carrier {
1778
1785
 
1779
1786
  // ---- the verbs
1780
1787
 
1781
- async invite({ name, ttl } = {}) {
1788
+ // short: the long code is parked at the relay (POST /park, relay/park.mjs) under a short code
1789
+ // (short.mjs) for SHORT_TTL seconds, one fetch; refused, the invite is withdrawn as when its topic
1790
+ // is. A login of its own: the relay checks that the parked code is this agent's.
1791
+ async invite({ name, ttl, short = false } = {}) {
1782
1792
  const code = this.#locked(({ now, me, store }) => {
1783
1793
  const code = makeInvite({ did: me.current_did, relay: this.relay, now, ...(ttl !== undefined && { ttl }) });
1784
1794
  store.addInvite(code, name ?? `invite-${code.nonce.slice(1, 9)}`, now);
@@ -1792,14 +1802,39 @@ export class Carrier {
1792
1802
  const r = this.#refusedTopics.get(t);
1793
1803
  fail(r?.code ?? 'subscribe', `the relay did not let this agent claim the invite's topic${r ? ` (${relaySays(r.detail)})` : ''}`);
1794
1804
  }
1805
+ if (!short) return { code: code.text, did: code.did, relay: code.relay, exp: code.exp };
1806
+ const s = makeShort(), exp = Math.min(checkNow(this.clock()) + SHORT_TTL, code.exp), ep = endpointOf(code.relay, this.endpoints);
1807
+ const creds = await this.#credentials(code.relay, ep);
1808
+ 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
+ const check = typeof r.body?.check === 'string' ? r.body.check : null;
1810
+ if (r.status === 429) fail('rate', `POST /park: ${relaySays(r.body?.detail)}`);
1811
+ if ((r.status === 404 || r.status === 405) && check === null) fail('park', `${code.relay} takes no short codes: use the long code (invite --long)`);
1812
+ if (r.status !== 200) fail('connect', `POST /park answered ${r.status}`);
1813
+ if (r.body?.ok !== true) fail(PARK_CHECKS.has(check) ? check : 'park', `the relay refused the short code (${relaySays(`${check}: ${r.body?.detail}`)})`);
1814
+ return { code: code.text, did: code.did, relay: code.relay, exp: code.exp, short: formatShort(s), short_exp: exp };
1795
1815
  } catch (e) {
1796
1816
  try { this.#locked(({ store }) => store.cancelInvite(code.nonce)); } catch {}
1797
1817
  throw e;
1798
1818
  }
1799
- return { code: code.text, did: code.did, relay: code.relay, exp: code.exp };
1819
+ }
1820
+
1821
+ // The long code parked under a short one, at this agent's own relay (a short code names none):
1822
+ // GET /park/<code hash>, which the relay answers once. Whatever it answers is a code to parse
1823
+ // like any other (accept); the four words show whether the pairing is the inviter's.
1824
+ async unpark(text) {
1825
+ const ep = endpointOf(this.relay, this.endpoints);
1826
+ const r = await http(`${ep.http}/park/${codeHash(text)}`);
1827
+ if (r.status === 429) fail('rate', `GET /park: ${relaySays(r.body?.detail)}`);
1828
+ if (r.status === 404 && r.body?.check === 'park_unknown') {
1829
+ fail('park_unknown', `no invite waits under this short code at ${this.relay}: mistyped, used already, or older than 10 minutes. Ask for a new one (a code made at another relay works only as the long code: invite --long)`);
1830
+ }
1831
+ if (r.status === 404 || r.status === 405) fail('park', `${this.relay} takes no short codes: ask for the long code (invite --long)`);
1832
+ if (r.status !== 200 || r.body?.ok !== true || typeof r.body.invite !== 'string') fail('connect', `GET /park answered ${r.status}`);
1833
+ return r.body.invite;
1800
1834
  }
1801
1835
 
1802
1836
  async accept(text, { name, wait = 10 } = {}) {
1837
+ if (isShort(text)) text = await this.unpark(text);
1803
1838
  const { code, id, entry } = this.#locked(({ now, me, store, st }) => {
1804
1839
  const code = parseInvite(text, now);
1805
1840
  // This agent's own relay, and those its operator configured, are the operator's choice.
@@ -1861,7 +1896,7 @@ export class Carrier {
1861
1896
  const s = store.load().s;
1862
1897
  return {
1863
1898
  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 })),
1899
+ re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key) })),
1865
1900
  invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
1866
1901
  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 })),
1867
1902
  };
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sigelo-contact",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
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": [
@@ -40,32 +40,39 @@
40
40
  "./envelope.mjs": "./envelope.mjs",
41
41
  "./prekeys": "./prekeys.mjs",
42
42
  "./prekeys.mjs": "./prekeys.mjs",
43
+ "./short": "./short.mjs",
44
+ "./short.mjs": "./short.mjs",
43
45
  "./package.json": "./package.json"
44
46
  },
45
47
  "files": [
46
48
  "README.md",
49
+ "bip39-english.mjs",
47
50
  "carrier.mjs",
48
51
  "envelope.mjs",
49
52
  "invite.mjs",
50
53
  "kdf.mjs",
51
54
  "prekeys.mjs",
55
+ "short.mjs",
52
56
  "store.mjs",
53
57
  "fixtures/carrier-v0.json",
54
58
  "fixtures/envelope-v0.json",
55
59
  "fixtures/invite-v0.json",
60
+ "fixtures/short-code-v0.json",
56
61
  "gen-carrier.mjs",
57
62
  "gen-envelope.mjs",
58
63
  "gen-invite.mjs",
64
+ "gen-short.mjs",
59
65
  "test-carrier.mjs",
60
66
  "test-envelope.mjs",
61
- "test-invite.mjs"
67
+ "test-invite.mjs",
68
+ "test-short.mjs"
62
69
  ],
63
70
  "engines": {
64
71
  "node": ">=22.18"
65
72
  },
66
73
  "scripts": {
67
- "test": "node test-invite.mjs && node test-envelope.mjs && node test-carrier.mjs",
68
- "gen": "node gen-invite.mjs && node gen-envelope.mjs && node gen-carrier.mjs",
74
+ "test": "node test-invite.mjs && node test-envelope.mjs && node test-carrier.mjs && node test-short.mjs",
75
+ "gen": "node gen-invite.mjs && node gen-envelope.mjs && node gen-carrier.mjs && node gen-short.mjs",
69
76
  "prepack": "node ../release/prepack.mjs pre",
70
77
  "postpack": "node ../release/prepack.mjs post",
71
78
  "prepublishOnly": "node -e \"if(process.env.SIGELO_PUBLISH!=='1'){console.error('refusing: publish the release tarball (release/RELEASE.md) with SIGELO_PUBLISH=1');process.exit(1)}\""
@@ -75,6 +82,6 @@
75
82
  "@noble/hashes": "^2.4.0",
76
83
  "@noble/post-quantum": "^0.7.1",
77
84
  "mqtt": "^5.16.0",
78
- "sigelo": "^0.1.4"
85
+ "sigelo": "^0.1.5"
79
86
  }
80
87
  }
package/short.mjs ADDED
@@ -0,0 +1,76 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Short invite codes and the four words of a pairing, contract sigelo-park/0 (ROADMAP §8 item 1).
3
+ // No network here; the carrier parks and fetches (carrier.mjs invite, accept). Fixture and runner:
4
+ // fixtures/short-code-v0.json, gen-short.mjs, test-short.mjs.
5
+ //
6
+ // A short code is what a person can say on the phone: 8 characters of Crockford's base32 (no I,
7
+ // L, O, U), shown as K7F3-Q9ZP, 40 bits from a CSPRNG. It names no relay and no DID: it is a key
8
+ // under which the inviter parks the long code (invite.mjs) at its relay for SHORT_TTL seconds,
9
+ // fetched once. The relay stores it under codeHash(code) = hex SHA-256("sigelo-park/0" ‖ the
10
+ // normalised code), so the code itself never reaches the relay's memory or logs. 40 bits hash in
11
+ // seconds, though: the hash hides the code from a log reader, not from the relay, which holds the
12
+ // long code anyway (THREAT-MODEL.md §2.10).
13
+ //
14
+ // Input is read the way people write: case does not matter, I and L read as 1, O as 0, and
15
+ // spaces and dashes (any of the dashes a phone's keyboard substitutes) are ignored. U is no digit
16
+ // and is refused, as is anything else outside the alphabet.
17
+ //
18
+ // The four words: once a pairing completes, both sides derive them from `pair` (kdf.pairId, which
19
+ // binds the pairing key K and so both original DIDs): HKDF-SHA256(pair's 16 bytes, salt
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 = nobody, not even the relay, swapped the pairing.
22
+ import { randomBytes } from 'node:crypto';
23
+ import { hkdf } from '@noble/hashes/hkdf.js';
24
+ import { sha256 } from '@noble/hashes/sha2.js';
25
+ import { bytesToHex, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';
26
+ import { WORDS } from './bip39-english.mjs';
27
+ import { fail, unhex } from './kdf.mjs';
28
+
29
+ export const PARK_V = 'sigelo-park/0', FINGERPRINT_LABEL = 'sigelo-fingerprint/0';
30
+ export const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
31
+ // Seconds a parked code lives at the relay; it goes at its first fetch before that.
32
+ export const SHORT_TTL = 600, SHORT_LENGTH = 8;
33
+ const FOLD = { I: '1', L: '1', O: '0' };
34
+ // Whitespace, and the hyphen with every dash a phone or a word processor puts in its place.
35
+ const SEPARATORS = /[\s\-‐-―−]+/g;
36
+ // Longer input is no short code: refused before any work.
37
+ const MAX_INPUT = 64;
38
+
39
+ /** The canonical form of a short code ("K7F3Q9ZP"), or throws short_code. */
40
+ export function normaliseShort(text) {
41
+ if (typeof text !== 'string' || text.length > MAX_INPUT) fail('short_code', 'not a short code');
42
+ const s = text.replace(SEPARATORS, '').toUpperCase().replace(/[ILO]/g, (c) => FOLD[c]);
43
+ if (s.length !== SHORT_LENGTH) fail('short_code', `${s.length} characters, a short code has ${SHORT_LENGTH}`);
44
+ for (const ch of s) if (!ALPHABET.includes(ch)) fail('short_code', `${JSON.stringify(ch)} is not in a short code${ch === 'U' ? ' (no U: a typo?)' : ''}`);
45
+ return s;
46
+ }
47
+
48
+ /** Whether `text` reads as a short code (a long code starts sgl1 and runs to about 126 characters). */
49
+ export function isShort(text) {
50
+ try { normaliseShort(text); return true; } catch { return false; }
51
+ }
52
+
53
+ /** "K7F3Q9ZP" → "K7F3-Q9ZP", how it is shown. */
54
+ export const formatShort = (norm) => `${norm.slice(0, 4)}-${norm.slice(4)}`;
55
+
56
+ /** A new short code from 5 random bytes, 5 bits a character, most significant first. → its canonical form. */
57
+ export function makeShort(rng = randomBytes) {
58
+ const b = rng(5);
59
+ if (!(b instanceof Uint8Array) || b.length !== 5) fail('short_code', 'the random source must give 5 bytes');
60
+ let x = 0n;
61
+ for (const v of b) x = (x << 8n) | BigInt(v);
62
+ let out = '';
63
+ for (let i = SHORT_LENGTH - 1; i >= 0; i--) out += ALPHABET[Number((x >> BigInt(5 * i)) & 31n)];
64
+ return out;
65
+ }
66
+
67
+ /** The key the relay parks under: hex SHA-256("sigelo-park/0" ‖ the normalised code). */
68
+ export const codeHash = (text) => bytesToHex(sha256(concatBytes(utf8ToBytes(PARK_V), utf8ToBytes(normaliseShort(text)))));
69
+
70
+ /** The four words of a pairing, from its pair id (32 lowercase hex digits, kdf.pairId). */
71
+ export function fingerprint(pair) {
72
+ const b = hkdf(sha256, unhex(pair, 16, 'pair'), utf8ToBytes(FINGERPRINT_LABEL), new Uint8Array(0), 6);
73
+ let x = 0n;
74
+ for (const v of b) x = (x << 8n) | BigInt(v);
75
+ return [0, 1, 2, 3].map((i) => WORDS[Number((x >> BigInt(48 - 11 * (i + 1))) & 2047n)]).join(' ');
76
+ }
package/test-short.mjs ADDED
@@ -0,0 +1,140 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Short invite codes (short.mjs, contract sigelo-park/0): fixtures/short-code-v0.json against
3
+ // short.mjs, gen-short.mjs --check, the word list's hash; then, with the relay checkout beside
4
+ // contact/ (SIGELO_RELAY_DIR, else ../relay), the whole flow on a loopback relay: invite → short
5
+ // code → accept by the short code → paired → the same four words on both sides; one use; a wrong
6
+ // code; an expired one.
7
+ // node contact/test-short.mjs → ALL PASS (n)
8
+ import { spawnSync } from 'node:child_process';
9
+ import { createHash } from 'node:crypto';
10
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
11
+ import { tmpdir } from 'node:os';
12
+ import { dirname, join } from 'node:path';
13
+ import { fileURLToPath, pathToFileURL } from 'node:url';
14
+ import { keygen } from 'sigelo';
15
+ import { BIP39_SHA256, WORDS } from './bip39-english.mjs';
16
+ import { ALPHABET, SHORT_TTL, codeHash, fingerprint, formatShort, isShort, makeShort, normaliseShort } from './short.mjs';
17
+
18
+ const HERE = dirname(fileURLToPath(import.meta.url));
19
+ let count = 0;
20
+ const fails = [];
21
+ const ok = (cond, what) => { count++; if (!cond) fails.push(what); };
22
+ const checkOf = (f) => { try { f(); return 'accepted'; } catch (e) { return e.check ?? `exception ${e.constructor.name}: ${e.message}`; } };
23
+ const report = () => {
24
+ for (const f of fails) console.log('FAIL ' + f);
25
+ if (fails.length) { console.log(`${fails.length} FAILED, ${count - fails.length} passed`); process.exit(1); }
26
+ };
27
+
28
+ // ================================================================ the fixture
29
+ {
30
+ const gen = spawnSync(process.execPath, [join(HERE, 'gen-short.mjs'), '--check'], { encoding: 'utf8' });
31
+ ok(gen.status === 0, `gen-short.mjs --check: ${(gen.stderr || gen.stdout).trim()}`);
32
+ const F = JSON.parse(readFileSync(join(HERE, 'fixtures', 'short-code-v0.json'), 'utf8'));
33
+ ok(WORDS.length === 2048 && createHash('sha256').update(WORDS.join('\n') + '\n').digest('hex') === BIP39_SHA256 && Object.isFrozen(WORDS), 'the BIP-39 English list: 2048 words, its published SHA-256, frozen');
34
+ ok(F.alphabet === ALPHABET && !/[ILOU]/.test(ALPHABET) && new Set(ALPHABET).size === 32, 'Crockford base32: 32 digits, no I, L, O, U');
35
+ for (const c of F.codes) {
36
+ const norm = makeShort(() => new Uint8Array(Buffer.from(c.rng, 'hex')));
37
+ ok(norm === c.normalised && formatShort(norm) === c.code, `code ${c.label}: ${c.rng} → ${formatShort(norm)}, expected ${c.code}`);
38
+ ok(codeHash(c.code) === c.code_hash && codeHash(c.normalised) === c.code_hash && codeHash(c.code.toLowerCase()) === c.code_hash, `code ${c.label}: code_hash, shown, bare and lowercase alike`);
39
+ ok(isShort(c.code), `code ${c.label}: recognised as a short code`);
40
+ }
41
+ for (const n of F.normalise) {
42
+ const got = checkOf(() => normaliseShort(n.input));
43
+ if (n.error) ok(got === n.error && !isShort(n.input), `normalise ${n.case}: ${got}, expected ${n.error}`);
44
+ else ok(normaliseShort(n.input) === n.normalised && isShort(n.input), `normalise ${n.case}: ${JSON.stringify(n.input)} → ${checkOf(() => normaliseShort(n.input)) === 'accepted' ? normaliseShort(n.input) : got}, expected ${n.normalised}`);
45
+ }
46
+ for (const f of F.fingerprints) ok(fingerprint(f.pair) === f.words, `fingerprint ${f.case}: ${fingerprint(f.pair)}, expected ${f.words}`);
47
+ ok(checkOf(() => fingerprint('A2CF45BD3D6AEE6D6E3F14FFD2751924')) === 'pair' && checkOf(() => fingerprint('ab')) === 'pair', 'fingerprint: anything but 32 lowercase hex digits is refused (pair)');
48
+ ok(checkOf(() => normaliseShort(undefined)) === 'short_code' && checkOf(() => normaliseShort('0'.repeat(65))) === 'short_code', 'normalise: no string, or past 64 characters, is short_code');
49
+ ok(checkOf(() => makeShort(() => new Uint8Array(4))) === 'short_code', 'makeShort: a random source that gives fewer than 5 bytes is refused');
50
+ // The real source: 1,000 codes, all well formed, no repeat (40 bits).
51
+ const seen = new Set();
52
+ for (let i = 0; i < 1000; i++) seen.add(makeShort());
53
+ ok(seen.size === 1000 && [...seen].every((s) => /^[0-9A-HJKMNP-TV-Z]{8}$/.test(s)), 'makeShort: 1,000 codes from the CSPRNG, all 8 Crockford digits, no repeat');
54
+ ok(SHORT_TTL === 600, 'a short code lives 10 minutes');
55
+ }
56
+
57
+ const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', 'relay');
58
+ if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
59
+ report();
60
+ console.log(`ALL PASS (${count}): the fixture part; SKIP the flow, no relay checkout beside contact/: set SIGELO_RELAY_DIR`);
61
+ process.exit(0);
62
+ }
63
+
64
+ // ================================================================ the flow, on a loopback relay
65
+ const { startRelay } = await import(pathToFileURL(join(RELAY_DIR, 'server.mjs')).href);
66
+ const { relayPolicy } = await import(pathToFileURL(join(RELAY_DIR, 'allowance.mjs')).href);
67
+ const { Carrier, pathsFor } = await import('./carrier.mjs');
68
+ setTimeout(() => { console.log(`FAIL the run did not finish in 120 s (${count} checks so far)`); process.exit(1); }, 120000).unref();
69
+
70
+ const HOST = 'relay.test', CREATED = '2026-10-01T00:00:00Z';
71
+ const dir = mkdtempSync(join(tmpdir(), 'sigelo-short-'));
72
+ let now = Date.parse('2026-10-14T12:00:00Z') / 1000;
73
+ const lines = [];
74
+ const relay = await startRelay({ host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
75
+ log: (l) => lines.push(l), policy: (ctx) => relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 } }) });
76
+ const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
77
+ const seed = (l) => new Uint8Array(createHash('sha256').update(`sigelo-short-test/0 ${l}`).digest());
78
+ function agent(label) {
79
+ const recovery = keygen({ seed: seed(`${label} recovery`), recovery: 'sha256:' + '0'.repeat(64), created: CREATED, nonce: seed(`${label} recovery nonce`).slice(0, 16) }).key;
80
+ const k = keygen({ seed: seed(label), recovery, created: CREATED, nonce: seed(`${label} nonce`).slice(0, 16) });
81
+ return { label, did: k.did, secret: k.secret, bundle: { v: 'sigelo/0', typ: 'bundle', genesis: k.genesis, rotations: [], bindings: [], attestations: [], issuers: [] } };
82
+ }
83
+ const events = {};
84
+ const make = (a) => {
85
+ events[a.label] = [];
86
+ return new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...pathsFor(join(dir, `${a.label}.local.json`)), relay: HOST, endpoints,
87
+ clock: () => now, onEvent: (e) => events[a.label].push(e), keep: true, backoff: [100, 400], retentionDays: 7 });
88
+ };
89
+ const refused = async (f) => { try { await f(); return 'accepted'; } catch (e) { return e.check ?? `exception ${e.message}`; } };
90
+ try {
91
+ const alice = agent('alice'), bob = agent('bob'), carol = agent('carol');
92
+ const ca = make(alice), cb = make(bob), cc = make(carol);
93
+ // alice: a short code by default, the long code beside it.
94
+ const inv = await ca.invite({ name: 'bob', short: true });
95
+ ok(/^[0-9A-HJKMNP-TV-Z]{4}-[0-9A-HJKMNP-TV-Z]{4}$/.test(inv.short ?? '') && /^sgl1/.test(inv.code) && inv.short_exp === now + SHORT_TTL, 'invite: a short code K7F3-Q9ZP, 10 minutes, beside the long one', JSON.stringify(inv));
96
+ ok(!lines.some((l) => l.includes(inv.short) || l.includes(normaliseShort(inv.short)) || l.includes(codeHash(inv.short)) || l.includes(inv.code)), 'the relay log holds neither the code, nor its hash, nor the long code');
97
+ // bob types it as heard: lowercase, no dash, an O for a 0 where there is one.
98
+ const typed = inv.short.toLowerCase().replace('-', ' ').replace(/0/g, 'o');
99
+ await ca.start();
100
+ const r = await cb.accept(typed, { name: 'alice', wait: 20 });
101
+ ok(r.status === 'connected' && r.contact?.did === alice.did, `accept by the short code, typed ${JSON.stringify(typed)}: connected to alice`);
102
+ ok(/^[a-z]+ [a-z]+ [a-z]+ [a-z]+$/.test(r.contact?.fingerprint ?? '') && r.contact.fingerprint.split(' ').every((w) => WORDS.includes(w)), 'accept returns four BIP-39 words', JSON.stringify(r));
103
+ await ca.stop();
104
+ const wordsOf = (c, did) => c.contacts().contacts.find((x) => x.did === did)?.fingerprint;
105
+ ok(wordsOf(ca, bob.did) === r.contact.fingerprint && wordsOf(cb, alice.did) === r.contact.fingerprint, 'contacts: both sides show the same four words');
106
+ const paired = events.alice.find((e) => e.type === 'paired');
107
+ ok(paired?.fingerprint === r.contact.fingerprint, 'the inviter\'s paired event carries the same four words');
108
+ // One use: carol tries the same code.
109
+ ok(await refused(() => cc.accept(inv.short, { wait: 1 })) === 'park_unknown', 'the same short code a second time: park_unknown');
110
+ // A code nobody parked.
111
+ ok(await refused(() => cc.accept(formatShort(makeShort()), { wait: 1 })) === 'park_unknown', 'a code nobody parked: park_unknown');
112
+ // Expiry: parked, then 10 minutes and a second pass.
113
+ const late = await ca.invite({ name: 'carol', short: true });
114
+ now += SHORT_TTL;
115
+ ok(await refused(() => cc.accept(late.short, { wait: 1 })) === 'park_unknown', 'a short code after its 10 minutes: park_unknown');
116
+ // An inviter whose clock runs a minute ahead of the relay's still parks (relay/park.mjs PARK_SKEW).
117
+ const ahead = new Carrier({ identity: () => ({ secret: alice.secret, bundle: alice.bundle }), ...pathsFor(join(dir, 'alice.local.json')), relay: HOST, endpoints,
118
+ clock: () => now + 60, keep: true, backoff: [100, 400], retentionDays: 7 });
119
+ const fast = await refused(() => ahead.invite({ name: 'carol', short: true }));
120
+ ok(fast === 'accepted', `an inviter's clock a minute ahead of the relay's: the short code parks (${fast})`);
121
+ await ahead.stop();
122
+ // --long: no parking at all.
123
+ const long = await ca.invite({ name: 'carol', short: false });
124
+ ok(long.short === undefined && /^sgl1/.test(long.code), 'invite without a short code (--long): the long code only');
125
+ // A long code is still accepted as before.
126
+ await ca.start();
127
+ const rl = await cc.accept(long.code, { name: 'alice', wait: 20 });
128
+ await ca.stop();
129
+ 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
+ ok(rl.contact.fingerprint !== r.contact.fingerprint, 'another pairing, other words');
131
+ // The database holds no short code and no long code (memory only).
132
+ const dump = readFileSync(join(dir, 'relay.db')).toString('latin1') + (existsSync(join(dir, 'relay.db-wal')) ? readFileSync(join(dir, 'relay.db-wal')).toString('latin1') : '');
133
+ 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');
134
+ for (const c of [cb, cc]) await c.stop();
135
+ } finally {
136
+ await relay.close();
137
+ rmSync(dir, { recursive: true, force: true });
138
+ }
139
+ report();
140
+ console.log(`ALL PASS (${count})`);