sigelo-contact 0.1.13 → 0.1.14

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.
@@ -0,0 +1,169 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Presence (carrier.mjs "Presence", design/transfer.md §8 T0): the store part first (off by default,
3
+ // allow and deny, own agents always, kept through a re-pair); then, with the relay checkout beside
4
+ // contact/ (SIGELO_RELAY_DIR, else ../relay), on a loopback relay: a started carrier's marker is
5
+ // read by an allowed contact and by its own agents, never by a denied one; a stop and a cut
6
+ // connection are the relay's offline with its time; a reconnection is online again; a deny clears
7
+ // what the contact sees.
8
+ // node contact/test-presence.mjs → ALL PASS (n)
9
+ import { createHash } from 'node:crypto';
10
+ import { existsSync, mkdtempSync, 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 { attest, keygen, verify } from 'sigelo';
15
+ import { Contacts, OPERATOR_CTX } from './store.mjs';
16
+
17
+ const HERE = dirname(fileURLToPath(import.meta.url));
18
+ let count = 0;
19
+ const fails = [];
20
+ const ok = (cond, what) => { count++; if (!cond) fails.push(what); };
21
+ const checkOf = (f) => { try { f(); return 'accepted'; } catch (e) { return e.check ?? `exception ${e.constructor.name}: ${e.message}`; } };
22
+ const report = () => {
23
+ for (const f of fails) console.log('FAIL ' + f);
24
+ if (fails.length) { console.log(`${fails.length} FAILED, ${count - fails.length} passed`); process.exit(1); }
25
+ };
26
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27
+ const until = async (cond, ms = 8000) => { const end = Date.now() + ms; while (Date.now() < end) { if (cond()) return true; await sleep(25); } return cond(); };
28
+
29
+ const CREATED = '2026-10-01T00:00:00Z', DAY = 86400;
30
+ let now = Date.parse('2026-11-02T12:00:00Z') / 1000;
31
+ const seed = (l) => new Uint8Array(createHash('sha256').update(`sigelo-presence-test/0 ${l}`).digest());
32
+ function agent(label) {
33
+ const k = keygen({ seed: seed(label), recovery: 'sha256:' + '0'.repeat(64), created: CREATED, nonce: seed(`${label} nonce`).slice(0, 16) });
34
+ return { label, did: k.did, secret: k.secret, genesis: k.genesis, bundle: { v: 'sigelo/0', typ: 'bundle', genesis: k.genesis, rotations: [], bindings: [], attestations: [], issuers: [] } };
35
+ }
36
+ const operate = (op, a, days = 90, iat = now - 60) => {
37
+ a.bundle.attestations.push(attest({ secret: op.secret, iss: op.did, sub: a.did, iat, exp: iat + days * DAY, ctx: OPERATOR_CTX, admission: 'invite', admission_by: op.did, claims: { relay: 'relay.test' } }));
38
+ if (!a.bundle.issuers.some((g) => g === op.genesis)) a.bundle.issuers.push(op.genesis);
39
+ };
40
+ const chainOnly = (a) => ({ ...a.bundle, attestations: [], issuers: [] });
41
+
42
+ // ================================================================ the store
43
+ {
44
+ const dir = mkdtempSync(join(tmpdir(), 'sigelo-presence-store-'));
45
+ try {
46
+ const H = agent('store human'), A = agent('store agent'), F = agent('store friend');
47
+ const hs = new Contacts(join(dir, 'h.json'), H.did, { mine: () => ({ chain: [H.did], operators: [] }) });
48
+ const key = (n) => n.toString(16).padStart(64, '0');
49
+ hs.admit(chainOnly(F), verify(chainOnly(F), now), 'friend', { relay: 'relay.test', pair_key: key(1) }, now);
50
+ operate(H, A);
51
+ hs.admit(A.bundle, verify(A.bundle, now), 'agent', { relay: 'relay.test', pair_key: key(2) }, now);
52
+ const c = () => hs.load().s.contacts;
53
+ ok(hs.presenceOf(c()[F.did], now) === 'deny' && hs.presenceOf(c()[A.did], now) === 'own', 'presence: a contact sees nothing by default (deny); an own agent always (own)');
54
+ ok(JSON.stringify(hs.setPresence('friend', true, now)) === JSON.stringify({ did: F.did, name: 'friend', presence: 'allow' }) && c()[F.did].presence === true, 'setPresence allow by name → {did, name, presence: allow}, kept in the record');
55
+ hs.admit(chainOnly(F), verify(chainOnly(F), now), 'friend', { relay: 'relay.test', pair_key: key(3) }, now);
56
+ ok(hs.presenceOf(c()[F.did], now) === 'allow', 'a re-pair keeps the choice');
57
+ ok(hs.setPresence(F.did, false, now).presence === 'deny' && c()[F.did].presence === undefined, 'setPresence deny by DID: off again');
58
+ ok(checkOf(() => hs.setPresence('agent', false, now)) === 'presence_own' && hs.setPresence('agent', true, now).presence === 'own', 'deny on an own agent: presence_own (own agents always see each other)');
59
+ ok(checkOf(() => hs.setPresence('nobody', true, now)) === 'not_contact' && checkOf(() => hs.setPresence('friend', 'yes', now)) === 'presence', 'no such contact: not_contact; allow not a boolean: presence');
60
+ } finally { rmSync(dir, { recursive: true, force: true }); }
61
+ }
62
+
63
+ const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', 'relay');
64
+ if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
65
+ report();
66
+ console.log(`ALL PASS (${count}): the store part; SKIP the rest, no relay checkout beside contact/ (the relay is its own AGPL package): set SIGELO_RELAY_DIR`);
67
+ process.exit(0);
68
+ }
69
+
70
+ // ================================================================ on a loopback relay
71
+ const { startRelay } = await import(pathToFileURL(join(RELAY_DIR, 'server.mjs')).href);
72
+ const { relayPolicy } = await import(pathToFileURL(join(RELAY_DIR, 'allowance.mjs')).href);
73
+ const { Carrier, pathsFor, presenceTopic } = await import('./carrier.mjs');
74
+ setTimeout(() => { console.log(`FAIL the run did not finish in 300 s (${count} checks so far)`); process.exit(1); }, 300000).unref();
75
+
76
+ const HOST = 'relay.test';
77
+ const dir = mkdtempSync(join(tmpdir(), 'sigelo-presence-'));
78
+ const relay = await startRelay({ host: HOST, db: join(dir, 'relay.db'), tcpPort: 0, httpPort: 0, loginRate: 100000, verifyBudget: 1e9, clock: () => now, diskUsed: () => 0.1,
79
+ log: () => {}, policy: (ctx) => relayPolicy(ctx, { pow: { bits: 8, loadBits: 12, loadPerHour: 1000 } }) });
80
+ const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
81
+ const events = {};
82
+ const make = (a) => {
83
+ events[a.label] = [];
84
+ return new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...pathsFor(join(dir, `${a.label}.local.json`)), relay: HOST, endpoints,
85
+ clock: () => now, onEvent: (e) => events[a.label].push(e), keep: true, backoff: [100, 400], retentionDays: 7 });
86
+ };
87
+ const of = (c, did) => c.contacts().contacts.find((x) => x.did === did);
88
+ async function pair(ci, ca, name, back) {
89
+ const inv = await ci.invite({ name });
90
+ await ca.accept(inv.code, { name: back, wait: 0.3 });
91
+ await ci.inbox(); await ca.inbox(); await ci.inbox();
92
+ }
93
+ const rounds = async (...cs) => { for (let i = 0; i < 4; i++) for (const c of cs) { now += 5; await c.inbox(); } };
94
+ // The relay's session of identity a, by its client id (carrier.mjs clientIdOf).
95
+ const sessionOf = (a) => relay.broker.clients['s' + createHash('sha256').update(a.did).digest('hex').slice(0, 24)];
96
+ try {
97
+ const H = agent('human'), A = agent('atlas'), B = agent('beacon'), F = agent('friend');
98
+ operate(H, A); operate(H, B);
99
+ const ca = make(A), cb = make(B), cf = make(F);
100
+ await pair(ca, cb, 'beacon', 'atlas');
101
+ await rounds(ca, cb);
102
+ await pair(ca, cf, 'friend', 'atlas');
103
+ await rounds(ca, cf);
104
+ ok(of(ca, B.did).tier === 'own' && of(cb, A.did).tier === 'own' && of(ca, F.did).tier === 'friend', 'set-up: atlas and beacon are own to each other (one operator), friend is friend');
105
+ ok(of(ca, B.did).presence === 'own' && of(ca, F.did).presence === 'deny' && of(ca, F.did).online === null, 'contacts(): presence own for an own agent, deny for a friend by default; online null while nothing is read');
106
+
107
+ // A short session (inbox) is never online: no will, no marker; and it reads none (it would forget it
108
+ // at once, and each subscribe draws on the relay's brake).
109
+ const subscribed = [];
110
+ relay.broker.on('subscribe', (subs) => { for (const x of subs) subscribed.push(x.topic); });
111
+ now += 5; await ca.inbox(); await cb.inbox();
112
+ ok(relay.presence.size === 0, 'presence: CLI-style sessions (not started) publish no marker');
113
+ ok(!subscribed.some((t) => t.startsWith('p/')), `presence: CLI-style sessions subscribe to no presence topic (${subscribed.filter((t) => t.startsWith('p/')).length})`);
114
+
115
+ const at0 = now;
116
+ await ca.start(); await cb.start(); await cf.start();
117
+ ok(await until(() => of(ca, B.did).online === true && of(cb, A.did).online === true), 'presence: two own agents, started, see each other online');
118
+ ok(subscribed.filter((t) => t.startsWith('p/')).length >= 3, 'presence: a started carrier subscribes to its contacts\' markers');
119
+ ok(of(ca, B.did).online_since === at0 && of(ca, B.did).last_seen === null, `online_since: when the writer connected (${of(ca, B.did).online_since})`);
120
+ await sleep(300);
121
+ ok(of(ca, F.did).online === null && of(cf, A.did).online === null, 'presence: neither atlas nor friend allowed the other: each reads nothing of the other (null), both started');
122
+ ok(events.atlas.some((e) => e.type === 'presence' && e.did === B.did && e.online === true), 'a presence event says so (onEvent; never kept for inbox)');
123
+ // The denied reader learns nothing: no marker toward it exists at the relay.
124
+ const fK = Buffer.from(JSON.parse((await import('node:fs')).readFileSync(pathsFor(join(dir, 'friend.local.json')).store, 'utf8')).contacts[A.did].pair_key, 'hex');
125
+ ok(!relay.presence.held([presenceTopic(fK, F.did, A.did)]).length, 'presence: no marker from friend toward atlas is held at the relay');
126
+
127
+ // friend allows atlas: atlas sees friend.
128
+ cf.setPresence('atlas', true);
129
+ ok(await until(() => of(ca, F.did).online === true), 'presence: friend allows atlas (setPresence): atlas sees friend online at once (a started carrier applies it)');
130
+ ok(of(cf, A.did).presence === 'allow', 'contacts(): presence allow');
131
+
132
+ // A clean stop: the relay's offline, with its time.
133
+ now += 60;
134
+ const stopAt = now;
135
+ await cb.stop();
136
+ ok(await until(() => of(ca, B.did).online === false) && of(ca, B.did).last_seen === stopAt, `presence: beacon stops: atlas reads offline, last seen at the relay's time (${of(ca, B.did).last_seen})`);
137
+ ok(events.atlas.some((e) => e.type === 'presence' && e.did === B.did && e.online === false && e.last_seen === stopAt), 'the event carries last_seen');
138
+
139
+ // Reconnect: online again.
140
+ now += 60;
141
+ await cb.start();
142
+ ok(await until(() => of(ca, B.did).online === true && of(ca, B.did).online_since === now), 'presence: beacon starts again: online, since the new connection');
143
+
144
+ // A cut (no DISCONNECT): the will. The carrier reconnects by itself (backoff), online again.
145
+ now += 60;
146
+ const cutAt = now;
147
+ sessionOf(B).conn.destroy();
148
+ ok(await until(() => events.atlas.some((e) => e.type === 'presence' && e.did === B.did && e.online === false && e.last_seen === cutAt)), 'presence: beacon\'s connection cut: the relay\'s will says offline at the cut');
149
+ ok(await until(() => of(ca, B.did).online === true), 'presence: beacon reconnects with backoff: online again');
150
+
151
+ // friend denies atlas: the marker is cleared, atlas knows nothing (null), not "offline".
152
+ cf.setPresence('atlas', false);
153
+ ok(await until(() => of(ca, F.did).online === null), 'presence: friend denies atlas: cleared at once, atlas reads nothing (online null, no last seen)');
154
+ ok(of(ca, F.did).last_seen === null, 'and no last seen either');
155
+ // Nor after friend leaves: nothing toward atlas to mark offline.
156
+ await cf.stop();
157
+ await sleep(300);
158
+ ok(of(ca, F.did).online === null && of(ca, F.did).last_seen === null, 'presence: a denied contact\'s stop tells atlas nothing');
159
+
160
+ // The reader's own connection drops: what it read is forgotten (null), not left "online".
161
+ await ca.stop();
162
+ ok(of(ca, B.did).online === null, 'presence: once the reader is offline, it reports nothing it cannot know (null)');
163
+ await cb.stop();
164
+ } finally {
165
+ await relay.close();
166
+ rmSync(dir, { recursive: true, force: true });
167
+ }
168
+ report();
169
+ console.log(`ALL PASS (${count})`);
package/test-short.mjs CHANGED
@@ -17,7 +17,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
17
17
  import { attest, keygen } from 'sigelo';
18
18
  import { BIP39_SHA256, WORDS } from './bip39-english.mjs';
19
19
  import { makeInvite } from './invite.mjs';
20
- import { ALPHABET, GIFT_V, SHORT_TTL, TAG_LABEL, codeHash, codeKind, fingerprint, formatGift, formatShort, giftHash, isShort, makeShort, normaliseGift, normaliseShort, relayTag, tagOf } from './short.mjs';
20
+ import { ALPHABET, GIFT_V, SHORT_TTL, TAG_LABEL, codeHash, codeKind, didWords, fingerprint, formatGift, formatShort, giftHash, isShort, makeShort, normaliseGift, normaliseShort, relayTag, tagOf } from './short.mjs';
21
21
  import { RELEASE_DID, REGISTRY_CTX, REGISTRY_URL, checkRegistry, loadRegistry, readTable, remember, resolveTag } from './relays.mjs';
22
22
  import { createServer } from 'node:http';
23
23
  import { did as didOf, parse as parseJson } from 'sigelo';
@@ -54,6 +54,9 @@ const report = () => {
54
54
  }
55
55
  for (const f of F.fingerprints) ok(fingerprint(f.pair) === f.words, `fingerprint ${f.case}: ${fingerprint(f.pair)}, expected ${f.words}`);
56
56
  ok(checkOf(() => fingerprint('A2CF45BD3D6AEE6D6E3F14FFD2751924')) === 'pair' && checkOf(() => fingerprint('ab')) === 'pair', 'fingerprint: anything but 32 lowercase hex digits is refused (pair)');
57
+ // The four words of a DID (an app's profile list): fixed for a DID, four list words, another DID others; a non-DID refused.
58
+ const dw = didWords('did:sigelo:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK'), dw2 = didWords('did:sigelo:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doL');
59
+ ok(dw === didWords('did:sigelo:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK') && dw.split(' ').length === 4 && dw !== dw2 && checkOf(() => didWords('did:web:x')) === 'did', `didWords: four words per DID (${dw} / ${dw2}), a non-DID refused`);
57
60
  ok(checkOf(() => normaliseShort(undefined)) === 'short_code' && checkOf(() => normaliseShort('0'.repeat(65))) === 'short_code', 'normalise: no string, or past 64 characters, is short_code');
58
61
  ok(checkOf(() => makeShort(() => new Uint8Array(4))) === 'short_code', 'makeShort: a random source that gives fewer than 5 bytes is refused');
59
62
  // The real source: 1,000 codes, all well formed, no repeat (40 bits).