sigelo-contact 0.1.20 → 0.1.21
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/call.mjs +126 -22
- package/carrier.mjs +106 -30
- package/package.json +2 -2
- package/page.mjs +113 -19
- package/rtc-web.mjs +19 -5
- package/test-group.mjs +13 -2
- package/test-relay-lane.mjs +76 -1
- package/test-transfer-web.mjs +71 -4
- package/test-transfer.mjs +13 -1
- package/test-voice.mjs +3 -0
- package/transfer-engine.mjs +77 -19
- package/transfer-node.mjs +14 -5
- package/transfer.mjs +7 -5
- package/voice.mjs +7 -2
package/page.mjs
CHANGED
|
@@ -65,6 +65,9 @@
|
|
|
65
65
|
// data.calls[did] true | false, else the default: off for a quiet contact, else data.settings.calls (default on).
|
|
66
66
|
// A call's chat line is a history record { kind: in | out, label CALL_LABEL, text "Call · 3:12" | "Missed call" | …,
|
|
67
67
|
// call: { id, state, secs } }; only a missed one counts as unread (a call taken or made here was seen).
|
|
68
|
+
// "Always relay my media" (design/calls.md §6, UI-API.md "Settings"): data.settings.relay_media, per profile (default
|
|
69
|
+
// off); SIGELO_ICE_POLICY=relay in the host's environment says the same. On: GET /api/calls/turn answers policy
|
|
70
|
+
// "relay" and the transfer engine is given it (relayMedia): every WebRTC lane only through the relay's TURN.
|
|
68
71
|
//
|
|
69
72
|
// Proof of work (design/profiles.md §6): what the human starts here (the page's start, a code, an
|
|
70
73
|
// answer, "Try now") passes the carrier's `started: 'user'`; past the day's three the route answers
|
|
@@ -105,6 +108,12 @@
|
|
|
105
108
|
// summary, exp, text}, QUESTION_LABEL {question, options?, text}; checked (promptOf), kept as `approval` / `question`
|
|
106
109
|
// beside a one-line text; the page's buttons answer with a reply's text (`yes CODE`, an option). Malformed: shown as data.
|
|
107
110
|
//
|
|
111
|
+
// A hosted agent's settings (UI-API.md "Agent settings"; sigelo-agent-host.ts): HOST_CAPS_LABEL {fields: [{key, value,
|
|
112
|
+
// options: [{value, label}], off?, next?}], note?}, sent only to a page whose receipts said host: true (carrier.mjs
|
|
113
|
+
// host_peer); checked (capsOf: keys model, effort, permissionMode; others dropped), kept as data.host[did], never in the
|
|
114
|
+
// history; the contact's `host`. POST /api/host/set sends HOST_SET_LABEL {key, value} (a choice it offered) and marks it
|
|
115
|
+
// next until the agent says again. A HOST_SET_LABEL that reaches a page: dropped (a page hosts nothing).
|
|
116
|
+
//
|
|
108
117
|
// The public invite (UI-API.md "Public invite"): a public code (sigelo-public/0, carrier.mjs invitePublic), PUB-…
|
|
109
118
|
// with the four words and a link, for 1, 6 or 12 months, Pro only, kept in the contact store; each use a request to
|
|
110
119
|
// approve (/api/public/approve, /refuse) unless open; Pause and the cap: /api/public/set; Stop for good (Revoke for
|
|
@@ -125,8 +134,8 @@
|
|
|
125
134
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
126
135
|
import { bytesToHex, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
127
136
|
import { canonicalize, did as didOf, parseBytes, verify, verifySig } from 'sigelo';
|
|
128
|
-
import { CALL_LABEL, CALL_SEND, DEFAULT_RELAY, POW_COST, POW_EVAL_MS, RE_LABEL, quoteHash, reLabel } from './carrier.mjs';
|
|
129
|
-
import { Line, callRoutes, stunOf } from './call.mjs';
|
|
137
|
+
import { CALL_LABEL, CALL_SEND, DEFAULT_RELAY, KINDS, POW_COST, POW_EVAL_MS, RE_LABEL, quoteHash, reLabel } from './carrier.mjs';
|
|
138
|
+
import { Line, callRoutes, policyOf, stunOf } from './call.mjs';
|
|
130
139
|
import { signAs } from './kdf.mjs';
|
|
131
140
|
import * as E from './enrol.mjs';
|
|
132
141
|
import { checkRelay } from './invite.mjs';
|
|
@@ -154,6 +163,8 @@ export const refuse = (status, check, message) => { throw Object.assign(new Erro
|
|
|
154
163
|
// ---- pictures and signed statements (the header's)
|
|
155
164
|
export const PICTURE_LABEL = 'sigelo-picture/0', STATEMENT_LABEL = 'sigelo-statement/0', PICTURE_MAX = 64 * 1024, STATEMENT_MAX = 10_000;
|
|
156
165
|
const PICTURE_TYPES = new Set(['image/jpeg', 'image/webp']);
|
|
166
|
+
/** A received file the page reads whole to save it (GET /api/files/data): at most this. */
|
|
167
|
+
export const FILE_DATA_MAX = 64 * 2 ** 20;
|
|
157
168
|
const b64 = (bytes) => { let t = ''; for (let i = 0; i < bytes.length; i += 0x8000) t += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(t); };
|
|
158
169
|
const unb64 = (t) => Uint8Array.from(atob(t), (c) => c.charCodeAt(0));
|
|
159
170
|
const b64url = (bytes) => b64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
@@ -185,6 +196,22 @@ export function promptOf(label, c) {
|
|
|
185
196
|
}
|
|
186
197
|
return null;
|
|
187
198
|
}
|
|
199
|
+
export const HOST_CAPS_LABEL = 'sigelo-host-caps/0', HOST_SET_LABEL = 'sigelo-host-set/0';
|
|
200
|
+
const HOST_KEYS = new Set(['model', 'effort', 'permissionMode']);
|
|
201
|
+
/** A hosted agent's settings as it announced them → {fields, note?} (a key not known here dropped), or null (malformed). */
|
|
202
|
+
export function capsOf(c) {
|
|
203
|
+
if (typeof c !== 'object' || c === null || Array.isArray(c) || !Array.isArray(c.fields) || c.fields.length > 16) return null;
|
|
204
|
+
const str = (v, max) => typeof v === 'string' && v.length <= max, fields = [];
|
|
205
|
+
for (const f of c.fields) {
|
|
206
|
+
if (typeof f !== 'object' || f === null || !str(f.key, 40) || !str(f.value, 200) || !Array.isArray(f.options) || f.options.length > 100
|
|
207
|
+
|| !f.options.every((o) => typeof o === 'object' && o !== null && str(o.value, 200) && str(o.label, 80))
|
|
208
|
+
|| (f.off !== undefined && !str(f.off, 120)) || (f.next !== undefined && !str(f.next, 200))) return null;
|
|
209
|
+
if (!HOST_KEYS.has(f.key) || fields.some((x) => x.key === f.key)) continue;
|
|
210
|
+
fields.push({ key: f.key, value: f.value, options: f.options.map((o) => ({ value: o.value, label: o.label })), ...(f.off !== undefined && { off: f.off }), ...(f.next !== undefined && { next: f.next }) });
|
|
211
|
+
}
|
|
212
|
+
if (c.note !== undefined && !str(c.note, 120)) return null;
|
|
213
|
+
return { fields, ...(c.note !== undefined && { note: c.note }) };
|
|
214
|
+
}
|
|
188
215
|
const chainOnly = (b) => ({ v: 'sigelo/0', typ: 'bundle', genesis: b.genesis, rotations: b.rotations ?? [], bindings: [], attestations: [], issuers: [] });
|
|
189
216
|
const SIGNED_LINE = /\n-- Signed with sigelo by [a-z]+ [a-z]+ [a-z]+ [a-z]+\. Check it in the sigelo app\.\s*$/;
|
|
190
217
|
/** A statement signed now by identity id ({sign | secret, bundle}, the carrier's): → its portable text. */
|
|
@@ -286,7 +313,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
286
313
|
};
|
|
287
314
|
let data;
|
|
288
315
|
try { data = JSON.parse(store.readData() ?? 'null') ?? {}; } catch { data = {}; }
|
|
289
|
-
for (const k of ['tags', 'checked', 'read', 'controls', 'settings', 'gread', 'seen', 'notify', 'kind', 'pics', 'pic_sent', 'pic_peer']) data[k] ??= {};
|
|
316
|
+
for (const k of ['tags', 'checked', 'read', 'controls', 'settings', 'gread', 'seen', 'notify', 'kind', 'pics', 'pic_sent', 'pic_peer', 'host']) data[k] ??= {};
|
|
290
317
|
data.gnotices ??= [];
|
|
291
318
|
delete data.waiting; // kept by an earlier page; the carrier says it now (contacts: prekeys, waiting)
|
|
292
319
|
const saveData = () => store.writeData(JSON.stringify(data));
|
|
@@ -329,6 +356,9 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
329
356
|
if (hidden({ did: m['from'], name: m['name'] })) continue;
|
|
330
357
|
// A contact's own picture (the header's "Pictures"): kept apart, never in the history.
|
|
331
358
|
if (m['label'] === PICTURE_LABEL) { takePicture(m); continue; }
|
|
359
|
+
// A hosted agent's settings (the header's): kept apart, never in the history; a setting sent here, dropped.
|
|
360
|
+
if (m['label'] === HOST_CAPS_LABEL) { const h = capsOf(m['content']); if (h) { data.host[String(m['from'])] = { ...h, at: nowS() }; saveData(); changed(); } continue; }
|
|
361
|
+
if (m['label'] === HOST_SET_LABEL) continue;
|
|
332
362
|
// A photo's preview (photo.mjs): into the chat at once, the full file by its transfer.
|
|
333
363
|
if (m['label'] === PHOTO_LABEL) {
|
|
334
364
|
let ph = null;
|
|
@@ -352,7 +382,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
352
382
|
const lane = m['transfer'] ? (m['via'] ?? null) : 'relay';
|
|
353
383
|
if (!m['transfer']) { try { transfers?.engine.superseded?.(m); } catch {} }
|
|
354
384
|
record({ kind: 'in', did: m['from'], name: m['contact'], label: m['label'], text: `file ${String(m['name'])} (${String(m['size'])} bytes), saved at ${String(m['path'])}`,
|
|
355
|
-
file: { name: String(m['name']), size: Number(m['size']), sha256: String(m['sha256'] ?? ''), via: lane, transfer: m['transfer'] ?? null },
|
|
385
|
+
file: { name: String(m['name']), size: Number(m['size']), sha256: String(m['sha256'] ?? ''), via: lane, transfer: m['transfer'] ?? null },
|
|
386
|
+
...(typeof m['path'] === 'string' && { saved: m['path'] }), ...iat, ...link }); // saved: where GET /api/files/data reads it, never parsed from the text
|
|
356
387
|
}
|
|
357
388
|
else {
|
|
358
389
|
// A hosted agent's approval or question (promptOf): its fields beside a one-line text, which a reply quotes.
|
|
@@ -469,15 +500,25 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
469
500
|
};
|
|
470
501
|
// The accept rule's "words compared": the pairing's words as the human checked them here (Chats → the four words).
|
|
471
502
|
const compared = (did) => { const x = carrier.contacts().contacts.find((c) => c.did === did); return Boolean(x && x.pair !== null && x.pair !== undefined && data.checked?.[did] === x.pair); };
|
|
472
|
-
|
|
503
|
+
// "Always relay my media" (the header's): the setting, or SIGELO_ICE_POLICY=relay where the host has an environment.
|
|
504
|
+
const relayMedia = () => policyOf(data.settings.relay_media === true, globalThis.process?.env?.SIGELO_ICE_POLICY);
|
|
505
|
+
const transfers = hooks.transfers ? { lib: hooks.transfers.lib, engine: hooks.transfers.make(carrier, onTransfer, { compared, policy: relayMedia }) } : null;
|
|
473
506
|
// ---- calls (the header's): the Line, its messages taken from the carrier at each `call` event and each drain.
|
|
474
507
|
data.calls ??= {};
|
|
475
508
|
const liveContact = (d) => carrier.contacts().contacts.find((c) => c.did === d && !c.revoked) ?? null;
|
|
476
509
|
const canCall = (c) => (typeof data.calls[c.did] === 'boolean' ? data.calls[c.did] : c.tier === 'quiet' ? false : data.settings.calls !== false);
|
|
510
|
+
// Calls are between people (design/calls.md §1): a contact this page takes for an agent (its kind, as the chat list
|
|
511
|
+
// shows it: the human's choice, else my agent, a worker, a group's agent) is never rung from here and never rings here.
|
|
512
|
+
const personOf = (c) => {
|
|
513
|
+
const agent = (hooks.agents?.() ?? []).find((a) => a.did !== undefined && c.chain?.includes(a.did));
|
|
514
|
+
return kindOf(c, agent?.mine ?? null, rosterAgents()).kind === 'person';
|
|
515
|
+
};
|
|
477
516
|
const CH = hooks.calls ?? {};
|
|
478
517
|
const line = new Line({
|
|
479
518
|
send: (to, content) => carrier.send(to, content, { label: CALL_LABEL, internal: CALL_SEND, local: false }),
|
|
480
|
-
contact: liveContact, allowed: canCall,
|
|
519
|
+
contact: liveContact, allowed: canCall, person: personOf,
|
|
520
|
+
refused: ({ did, check }) => record({ kind: 'event', type: 'dropped', did, name: liveContact(did)?.name ?? null, code: check, detail: 'a call from an agent: refused (calls are between people)' }),
|
|
521
|
+
shares: (c) => c.presence === 'allow' || c.presence === 'own', me: () => hooks.me().original,
|
|
481
522
|
line: ({ did, dir, text, call }) => { record({ kind: dir, did, name: liveContact(did)?.name ?? null, text, label: CALL_LABEL, call }); },
|
|
482
523
|
alert: (x) => { try { CH.alert?.(x); } catch {} },
|
|
483
524
|
audio: (x) => { try { void Promise.resolve(CH.audio?.(x)).catch(() => {}); } catch {} },
|
|
@@ -532,7 +573,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
532
573
|
const publicInvite = (c) => c.publics?.[0] ?? null;
|
|
533
574
|
const walletSet = () => ({ wallet: data.settings.wallet === true, prices: data.settings.prices === true, currency: CURRENCIES.includes(data.settings.currency) ? data.settings.currency : null });
|
|
534
575
|
const settingsAll = () => ({ ...settings(), seen_receipts: receiptsOn(), notify: data.settings.notify !== false,
|
|
535
|
-
new_tier: TIER_NEW.has(data.settings.new_tier) ? data.settings.new_tier : 'friend', new_presence: data.settings.new_presence === true, calls: data.settings.calls !== false,
|
|
576
|
+
new_tier: TIER_NEW.has(data.settings.new_tier) ? data.settings.new_tier : 'friend', new_presence: data.settings.new_presence === true, calls: data.settings.calls !== false,
|
|
577
|
+
relay_media: relayMedia() === 'relay', ...walletSet() });
|
|
536
578
|
|
|
537
579
|
// ---- pictures (the header's): mine to the contacts that read them, theirs kept, a local one beside
|
|
538
580
|
const picFile = (key) => (key === 'me' ? 'me' : `${key[0]}-${bytesToHex(sha256(utf8ToBytes(key.slice(2)))).slice(0, 16)}`);
|
|
@@ -712,16 +754,18 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
712
754
|
};
|
|
713
755
|
// The contact holding a worker's original DID, live, or null.
|
|
714
756
|
const contactOfWorker = (w) => carrier.contacts().contacts.find((x) => !x.revoked && x.chain.includes(w.original)) ?? null;
|
|
715
|
-
// A contact's kind (UI-API.md "Kinds"):
|
|
716
|
-
//
|
|
717
|
-
//
|
|
757
|
+
// A contact's kind (UI-API.md "Kinds"): person, agent or desk (a support desk). The human's choice (POST /api/kind,
|
|
758
|
+
// data.kind) wins; else what the contact said of itself once paired (carrier.mjs "Kinds": kind_peer agent or desk);
|
|
759
|
+
// else an agent when the page knows it is one (my agent: ours by its operator attestation, on this machine, or a
|
|
760
|
+
// worker of my keeper root; a member a group roster names an agent); else a person.
|
|
718
761
|
let workerDids = new Set();
|
|
719
762
|
const rosterAgents = () => {
|
|
720
763
|
try { return new Set(G && groupsFile && carrier.platform.files.read(groupsFile) !== null ? G.list({ carrier, file: groupsFile }).flatMap((g) => g.members.filter((m) => m.role === 'agent').map((m) => m.did)) : []); } catch { return new Set(); }
|
|
721
764
|
};
|
|
722
765
|
const kindOf = (x, mine, roles) => {
|
|
723
766
|
const set = data.kind[x.did];
|
|
724
|
-
if (set
|
|
767
|
+
if (KINDS.includes(set)) return { kind: set, kind_set: true };
|
|
768
|
+
if (x.kind_peer === 'agent' || x.kind_peer === 'desk') return { kind: x.kind_peer, kind_set: false };
|
|
725
769
|
const agent = x.ours === true || mine !== null || x.chain.some((d) => workerDids.has(d) || roles.has(d));
|
|
726
770
|
return { kind: agent ? 'agent' : 'person', kind_set: false };
|
|
727
771
|
};
|
|
@@ -773,7 +817,9 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
773
817
|
last: last ? { dir: last.kind, text: textOf(last.text).slice(0, 200), at: last.at, status: statusOf(last, x.seen_upto), ...(last.call && { call: last.call.state }) } : null,
|
|
774
818
|
notify: notifyOf(x.did), seen_upto: x.seen_upto ?? null,
|
|
775
819
|
// A busy mark (carrier.mjs "Busy marks"): their agent works on a turn; the chat's wheel, never a message.
|
|
776
|
-
busy: x.busy === true,
|
|
820
|
+
busy: x.busy === true, busy_n: x.busy === true ? (x.busy_n ?? 1) : 0,
|
|
821
|
+
// A hosted agent's settings (the header's), as it last said them; null: it never did.
|
|
822
|
+
host: data.host[x.did] ?? null,
|
|
777
823
|
picture: picRev(picOf(x.did) ?? ''), picture_local: data.pics[`l:${x.did}`] !== undefined,
|
|
778
824
|
waiting, not_collected: queued.length, queued: x.queued,
|
|
779
825
|
status: x.re_pair ? 'pair_again' : waiting ? 'waiting' : queued.length ? 'not_collected' : 'ok', ours: x.ours === true || mine !== null, tier,
|
|
@@ -1193,10 +1239,24 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
1193
1239
|
if (typeof allow !== 'boolean') refuse(400, 'body', 'allow: true or false');
|
|
1194
1240
|
try { return carrier.setPresence(c.did, allow); } catch (e) { if (e.check === 'presence_own') e.status = 409; throw e; }
|
|
1195
1241
|
}),
|
|
1196
|
-
// A
|
|
1242
|
+
// A hosted agent's setting (the header's): one of the choices it offered; it applies it at its next turn.
|
|
1243
|
+
'POST /api/host/set': (b) => serial(async () => {
|
|
1244
|
+
const c = contactOf(b['contact']), h = data.host[c.did], key = b['key'], value = b['value'];
|
|
1245
|
+
if (!h) refuse(409, 'host_none', 'this contact has not said what can be set');
|
|
1246
|
+
const f = h.fields.find((x) => x.key === key) ?? refuse(400, 'body', `key: one of ${h.fields.map((x) => x.key).join(', ')}`);
|
|
1247
|
+
if (f.off !== undefined) refuse(409, 'host_off', f.off);
|
|
1248
|
+
if (typeof value !== 'string' || !f.options.some((o) => o.value === value)) refuse(400, 'body', 'value: one of its choices');
|
|
1249
|
+
const r = await carrier.send(c.did, { key, value }, { label: HOST_SET_LABEL });
|
|
1250
|
+
// Waiting for its next turn until the agent says again.
|
|
1251
|
+
if (value === f.value) delete f.next; else f.next = value;
|
|
1252
|
+
delete h.note;
|
|
1253
|
+
saveData(); changed();
|
|
1254
|
+
return { did: c.did, host: h, status: r.status };
|
|
1255
|
+
}),
|
|
1256
|
+
// A contact's kind, the human's choice (Chat settings → "This is"): person, agent, desk, or null (the page decides again).
|
|
1197
1257
|
'POST /api/kind': (b) => serial(async () => {
|
|
1198
1258
|
const c = contactOf(b['contact']), k = b['kind'];
|
|
1199
|
-
if (k
|
|
1259
|
+
if (!KINDS.includes(k) && k !== null) refuse(400, 'body', 'kind: person, agent, desk, or null (automatic)');
|
|
1200
1260
|
if (k === null) delete data.kind[c.did]; else data.kind[c.did] = k;
|
|
1201
1261
|
saveData(); changed();
|
|
1202
1262
|
return { did: c.did, kind: kindOf(c, null, rosterAgents()).kind, kind_set: k !== null };
|
|
@@ -1308,8 +1368,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
1308
1368
|
'GET /api/settings': () => settingsAll(),
|
|
1309
1369
|
// Any of: relay, seen_receipts, notify, new_tier, new_presence (Settings → Chats); wallet, prices, currency (Settings → Wallet); each checked before any is kept.
|
|
1310
1370
|
'POST /api/settings': (b) => serial(async () => {
|
|
1311
|
-
const v = b['relay'], flags = ['seen_receipts', 'notify', 'new_presence', 'wallet', 'prices', 'calls'].filter((k) => b[k] !== undefined), t = b['new_tier'], cur = b['currency'];
|
|
1312
|
-
if (v === undefined && flags.length === 0 && t === undefined && cur === undefined) refuse(400, 'body', 'relay: a host[:port], or "" for the default (or seen_receipts, notify, new_tier, new_presence, wallet, prices, currency, calls)');
|
|
1371
|
+
const v = b['relay'], flags = ['seen_receipts', 'notify', 'new_presence', 'wallet', 'prices', 'calls', 'relay_media'].filter((k) => b[k] !== undefined), t = b['new_tier'], cur = b['currency'];
|
|
1372
|
+
if (v === undefined && flags.length === 0 && t === undefined && cur === undefined) refuse(400, 'body', 'relay: a host[:port], or "" for the default (or seen_receipts, notify, new_tier, new_presence, wallet, prices, currency, calls, relay_media)');
|
|
1313
1373
|
for (const k of flags) if (typeof b[k] !== 'boolean') refuse(400, 'body', `${k}: true or false`);
|
|
1314
1374
|
if (t !== undefined && !TIER_NEW.has(t)) refuse(400, 'body', 'new_tier: own, friend or quiet');
|
|
1315
1375
|
if (cur !== undefined && cur !== null && !CURRENCIES.includes(cur)) refuse(400, 'body', `currency: one of ${CURRENCIES.join(', ')}`);
|
|
@@ -1323,6 +1383,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
1323
1383
|
if (b['notify'] !== undefined) data.settings.notify = b['notify'];
|
|
1324
1384
|
if (b['new_presence'] !== undefined) data.settings.new_presence = b['new_presence'];
|
|
1325
1385
|
if (b['calls'] !== undefined) data.settings.calls = b['calls'];
|
|
1386
|
+
if (b['relay_media'] !== undefined) data.settings.relay_media = b['relay_media'];
|
|
1326
1387
|
if (t !== undefined) data.settings.new_tier = t;
|
|
1327
1388
|
if (b['wallet'] !== undefined) data.settings.wallet = b['wallet'];
|
|
1328
1389
|
if (b['prices'] !== undefined) data.settings.prices = b['prices'];
|
|
@@ -1525,18 +1586,45 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
|
|
|
1525
1586
|
const callRouteSet = callRoutes({
|
|
1526
1587
|
line, contactOf: (v) => { const x = contactOf(v); return liveContact(x.did) ?? refuse(404, 'not_contact', 'not a contact'); },
|
|
1527
1588
|
callable: (c) => {
|
|
1528
|
-
if (
|
|
1589
|
+
if (!personOf(c)) return { check: 'call_agent', message: 'calls are between people: no calls to or from an agent' };
|
|
1529
1590
|
if (c.re_pair) return { check: 'call_pairing', message: 'pair again first' };
|
|
1530
1591
|
if (c.online !== true) return { check: 'call_offline', message: `${c.name} is not online now` };
|
|
1531
1592
|
return true;
|
|
1532
1593
|
},
|
|
1533
1594
|
stun: (c) => stunOf(carrier.relay, c?.relay),
|
|
1595
|
+
turn: () => (globalThis.process?.env?.SIGELO_TURN === 'off' ? null : carrier.turnServer?.() ?? null), // SIGELO_TURN=off: STUN alone (the transfer engine reads it too)
|
|
1596
|
+
policy: relayMedia,
|
|
1534
1597
|
can: { speaker: typeof CH.speaker === 'function', mic: typeof CH.mic === 'function', ring: typeof CH.alert === 'function' },
|
|
1535
1598
|
hooks: { speaker: CH.speaker, mic: CH.mic, micSettings: CH.micSettings },
|
|
1536
1599
|
allow: (c, on) => { if (on === null) delete data.calls[c.did]; else data.calls[c.did] = on; saveData(); changed(); },
|
|
1537
1600
|
allowOf: (c) => canCall(c),
|
|
1538
1601
|
});
|
|
1539
1602
|
for (const [k, f] of Object.entries(callRouteSet)) routes[k] = k.startsWith('POST ') ? (b, q) => gone(() => f(b, q))() : f;
|
|
1603
|
+
// A file received (2026-11-25, the bubble's "Save to Downloads"): its bytes, for the page to put where the owner takes it
|
|
1604
|
+
// from (the Android app: Downloads, through the shell's MediaStore; a tab or a computer's page: a download). By its chat
|
|
1605
|
+
// message (n) or its transfer (id); only a file under this identity's received files, at most FILE_DATA_MAX. Never remote.
|
|
1606
|
+
routes['GET /api/files/data'] = (_, q) => {
|
|
1607
|
+
let path = null, name = null, size = 0;
|
|
1608
|
+
const n = q.get('n'), id = q.get('id');
|
|
1609
|
+
if (n !== null) {
|
|
1610
|
+
const k = Number(n), r = Number.isSafeInteger(k) ? recs.find((x) => x.n === k && x.kind === 'in' && x.file) : undefined;
|
|
1611
|
+
if (!r) refuse(404, 'file_unknown', 'no file received in that message');
|
|
1612
|
+
({ name, size } = r.file);
|
|
1613
|
+
path = typeof r.saved === 'string' ? r.saved : null; // a field kept at receipt (the text holds the sender's file name)
|
|
1614
|
+
} else if (id !== null) {
|
|
1615
|
+
if (!transfers) refuse(404, 'transfer_unknown', 'no transfers here');
|
|
1616
|
+
if (!/^[0-9a-f]{32}$/.test(id)) refuse(400, 'body', 'id: a transfer id (32 hex digits)');
|
|
1617
|
+
const r = transfers.lib.list({ carrier, identity: hooks.transfers.identity }).in.find((x) => x.id === id && x.state === 'done') ?? refuse(404, 'transfer_unknown', 'no file received by that transfer');
|
|
1618
|
+
({ name, size } = r); path = r.saved ?? null;
|
|
1619
|
+
} else refuse(400, 'body', 'n: a chat message, or id: a transfer');
|
|
1620
|
+
if (typeof path === 'string' && path.startsWith('content:')) refuse(409, 'in_downloads', `${name} is in Downloads already`);
|
|
1621
|
+
const base = carrier.filesDir, rel = typeof path === 'string' && path.startsWith(`${base}/`) ? path.slice(base.length + 1) : null;
|
|
1622
|
+
if (rel === null || rel.startsWith('.') || rel.split('/').includes('..')) refuse(404, 'file_unknown', 'not a file received here');
|
|
1623
|
+
if (size > FILE_DATA_MAX) refuse(409, 'file_too_large', `${name} is over ${FILE_DATA_MAX / 2 ** 20} MiB: open it where it was saved`);
|
|
1624
|
+
const bytes = carrier.platform.files.read(path) ?? refuse(404, 'file_gone', `${name} is not here any more`);
|
|
1625
|
+
if (bytes.length > FILE_DATA_MAX) refuse(409, 'file_too_large', `${name} is over ${FILE_DATA_MAX / 2 ** 20} MiB: open it where it was saved`);
|
|
1626
|
+
return { name, size: bytes.length, data: b64(bytes) };
|
|
1627
|
+
};
|
|
1540
1628
|
if (transfers) Object.assign(routes, transferRoutes({ X: transfers.lib, engine: transfers.engine, host: hooks.transfers, carrier, identity: hooks.transfers.identity, serial, contactOf, changed, record, groups: G && groupsFile ? { G, file: groupsFile, list: groupsList } : null }));
|
|
1541
1629
|
if (G) Object.assign(routes, groupRoutes);
|
|
1542
1630
|
// One handler for every listener: the route's answer as [status, JSON value].
|
|
@@ -1637,8 +1725,14 @@ function transferRoutes({ X, engine, host, carrier, identity, serial, contactOf,
|
|
|
1637
1725
|
return strip(r);
|
|
1638
1726
|
})),
|
|
1639
1727
|
// The phone's own: a file picked (the system's picker), a photo taken (the system's camera), a file that landed opened.
|
|
1640
|
-
// images: the picker shows pictures only (the composer's Photo).
|
|
1641
|
-
|
|
1728
|
+
// images: the picker shows pictures only (the composer's Photo). multiple (2026-11-25): several at once → { docs: [...] },
|
|
1729
|
+
// each then sent as its own transfer (POST /api/transfers/send per doc, in order).
|
|
1730
|
+
...(docs && { 'POST /api/transfers/pick': (b) => serial(async () => {
|
|
1731
|
+
const multiple = b?.['multiple'] === true, x = await host.pick({ images: b?.['images'] === true, ...(multiple && { multiple: true }) });
|
|
1732
|
+
if (!multiple || x === null || x === undefined) return x ?? { cancelled: true };
|
|
1733
|
+
const list = Array.isArray(x) ? x : [x];
|
|
1734
|
+
return list.length ? { docs: list } : { cancelled: true };
|
|
1735
|
+
}) }),
|
|
1642
1736
|
// The microphone asked of the shell before the page records (Android: RECORD_AUDIO at the first); none elsewhere.
|
|
1643
1737
|
// Refused once, never asked again (the shell remembers): mic-settings opens the app's settings page instead.
|
|
1644
1738
|
...(typeof host.mic === 'function' && { 'POST /api/transfers/mic': async () => ({ granted: await host.mic() }) }),
|
package/rtc-web.mjs
CHANGED
|
@@ -3,7 +3,12 @@
|
|
|
3
3
|
// behind the interface of apps/transfer/rtc.mjs (werift, Node), so transfer-engine.mjs drives both alike
|
|
4
4
|
// and a phone talks to a Node agent or another phone over the same `sigelo-transfer/0` channel.
|
|
5
5
|
//
|
|
6
|
-
// const p = await peer({ stun, gatherMs, RTC }) RTC: the constructor (default globalThis.RTCPeerConnection)
|
|
6
|
+
// const p = await peer({ stun, turn, gatherMs, RTC, policy }) RTC: the constructor (default globalThis.RTCPeerConnection);
|
|
7
|
+
// turn: { urls, username, credential } (carrier.turnServer) or null;
|
|
8
|
+
// policy "relay" ("Always relay my media"): iceTransportPolicy relay, no
|
|
9
|
+
// STUN, relayed candidates only in what leaves (call.mjs relayOnly); refused
|
|
10
|
+
// relay_only without turn
|
|
11
|
+
// await p.relayed() → the selected pair has a relayed candidate (true), none (false), not known (null): call.mjs relayedOf
|
|
7
12
|
// await p.offer(label) → sdp; await p.answer(sdp, label) → sdp; await p.accept(sdp)
|
|
8
13
|
// await p.open(ms) → the channel (transfer.mjs's: send, buffered, close, on) once it is open, or throws ice_timeout
|
|
9
14
|
// p.close()
|
|
@@ -14,9 +19,15 @@
|
|
|
14
19
|
// address. The send buffer: the engine pauses above 4 MiB (transfer.mjs HIGH) and goes on below 1 MiB
|
|
15
20
|
// (bufferedamountlow); a browser closes a channel whose buffer passes 16 MiB, so neither is raised.
|
|
16
21
|
import { LOW } from './transfer.mjs';
|
|
22
|
+
import { RELAY_ONLY, relayOnly, relayedOf } from './call.mjs';
|
|
17
23
|
|
|
18
24
|
const fail = (check, why) => { throw Object.assign(new Error(`${check}: ${why}`), { check }); };
|
|
19
|
-
|
|
25
|
+
/** STUN ['host:port', …] and TURN ({ urls, username, credential } from the relay, or null) → RTCIceServer[]. The policy stays
|
|
26
|
+
* "all": a direct pair is preferred, the relayed candidate is used only when none answers. */
|
|
27
|
+
/** Browser and WebView DTLS checks the handshake signatures: TURN allowed here (apps/transfer/rtc.mjs: only with dtls-verify.mjs's checks in place). */
|
|
28
|
+
export const TURN_OK = true;
|
|
29
|
+
export const iceServers = (stun, turn = null) => [...(stun.length ? [{ urls: stun.map((s) => `stun:${s}`) }] : []),
|
|
30
|
+
...(turn ? [{ urls: [...turn.urls], username: turn.username, credential: turn.credential }] : [])];
|
|
20
31
|
export const noMdns = (sdp) => sdp.split(/\r?\n/).filter((l) => !/^a=candidate:.* [0-9a-f-]+\.local /i.test(l)).join('\r\n');
|
|
21
32
|
|
|
22
33
|
/** An RTCDataChannel as transfer.mjs's channel. */
|
|
@@ -39,9 +50,11 @@ export function channelOf(dc, pc) {
|
|
|
39
50
|
};
|
|
40
51
|
}
|
|
41
52
|
|
|
42
|
-
export async function peer({ stun = [], gatherMs = 3000, RTC = globalThis.RTCPeerConnection } = {}) {
|
|
53
|
+
export async function peer({ stun = [], turn = null, gatherMs = 3000, RTC = globalThis.RTCPeerConnection, policy = 'all' } = {}) {
|
|
43
54
|
if (typeof RTC !== 'function') fail('no_rtc', 'this page has no RTCPeerConnection');
|
|
44
|
-
const
|
|
55
|
+
const relay = policy === 'relay';
|
|
56
|
+
if (relay && !turn) throw Object.assign(new Error(RELAY_ONLY), { check: 'relay_only' });
|
|
57
|
+
const pc = new RTC({ iceServers: iceServers(relay ? [] : stun, turn), ...(relay && { iceTransportPolicy: 'relay' }) });
|
|
45
58
|
let dc = null, want = null, gotDc;
|
|
46
59
|
const dcP = new Promise((r) => { gotDc = r; });
|
|
47
60
|
pc.addEventListener('datachannel', (ev) => {
|
|
@@ -57,7 +70,7 @@ export async function peer({ stun = [], gatherMs = 3000, RTC = globalThis.RTCPee
|
|
|
57
70
|
pc.addEventListener('icegatheringstatechange', () => { if (pc.iceGatheringState === 'complete') { clearTimeout(t); r(); } });
|
|
58
71
|
});
|
|
59
72
|
}
|
|
60
|
-
return pc.localDescription.sdp;
|
|
73
|
+
return relay ? relayOnly(pc.localDescription.sdp) : pc.localDescription.sdp;
|
|
61
74
|
};
|
|
62
75
|
return {
|
|
63
76
|
pc,
|
|
@@ -90,6 +103,7 @@ export async function peer({ stun = [], gatherMs = 3000, RTC = globalThis.RTCPee
|
|
|
90
103
|
return channelOf(ch, pc);
|
|
91
104
|
} finally { clearTimeout(timer); }
|
|
92
105
|
},
|
|
106
|
+
async relayed() { try { return relayedOf(await pc.getStats()); } catch { return null; } },
|
|
93
107
|
close() { try { pc.close(); } catch {} },
|
|
94
108
|
};
|
|
95
109
|
}
|
package/test-group.mjs
CHANGED
|
@@ -112,7 +112,7 @@ const relay = await startRelay({ host: HOST, db: join(dir, 'relay.db'), tcpPort:
|
|
|
112
112
|
const endpoints = { [HOST]: { mqtt: `mqtt://127.0.0.1:${relay.ports.tcp}`, http: `http://127.0.0.1:${relay.ports.http}` } };
|
|
113
113
|
const make = (a) => {
|
|
114
114
|
const paths = pathsFor(join(dir, `${a.label}.local.json`));
|
|
115
|
-
a.c = new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...paths, relay: HOST, endpoints, clock: () => now, keep: true, backoff: [100, 400], retentionDays: 7, ...(a.selfName && { selfName: a.selfName }) });
|
|
115
|
+
a.c = new Carrier({ identity: () => ({ secret: a.secret, bundle: a.bundle }), ...paths, relay: HOST, endpoints, clock: () => now, keep: true, backoff: [100, 400], retentionDays: 7, ...(a.selfName && { selfName: a.selfName }), ...(a.selfKind !== undefined && { selfKind: a.selfKind }) });
|
|
116
116
|
a.f = groupsPath(join(dir, `${a.label}.local.json`)); a.paths = paths; a.out = []; a.seen = [];
|
|
117
117
|
return a;
|
|
118
118
|
};
|
|
@@ -403,7 +403,18 @@ try {
|
|
|
403
403
|
let creatorName = null;
|
|
404
404
|
for (let i = 0; i < 3 && creatorName !== 'Nora x'; i++) creatorName = await g4at4();
|
|
405
405
|
ok(creatorName === 'Nora x', `names: the creator's own name in the roster is its told one, not "creator" (${creatorName})`);
|
|
406
|
-
|
|
406
|
+
// ---- kinds (carrier.mjs "Kinds", 2026-11-26): a desk and an agent say so in the name's receipt; a person's app says
|
|
407
|
+
// nothing; the receiver keeps kind_peer; an unknown kind is ignored; a kind with no name is not taken for a receipt.
|
|
408
|
+
const K1 = make(Object.assign(agent('kinds person'), { selfName: 'Pia' })), K2 = make(Object.assign(agent('kinds desk'), { selfName: 'Help', selfKind: () => 'desk' }));
|
|
409
|
+
const K3 = make(Object.assign(agent('kinds agent'), { selfKind: 'agent' })), K4 = make(Object.assign(agent('kinds odd'), { selfName: 'Odd', selfKind: () => 'robot' }));
|
|
410
|
+
for (const x of [K2, K3, K4]) { const inv = await x.c.invite({}); await K1.c.accept(inv.code, { wait: 0.3 }); }
|
|
411
|
+
for (let i = 0; i < 3; i++) { now += 5; for (const x of [K1, K2, K3, K4]) await x.c.inbox(); }
|
|
412
|
+
ok(cOf(K1, K2)?.kind_peer === 'desk' && cOf(K1, K2).name === 'Help' && cOf(K1, K3)?.kind_peer === 'agent' && cOf(K1, K4)?.kind_peer === null,
|
|
413
|
+
`kinds: the desk's and the agent's said, kept as kind_peer; an unknown one ignored (${[cOf(K1, K2)?.kind_peer, cOf(K1, K3)?.kind_peer, cOf(K1, K4)?.kind_peer]})`);
|
|
414
|
+
ok([K2, K3, K4].every((x) => cOf(x, K1)?.kind_peer === null) && cOf(K1, K3).seen_peer === false, 'kinds: a person says nothing (null on the other side); a kind-only receipt is not a seen receipt');
|
|
415
|
+
ok(K2.c.selfKind() === 'desk' && K4.c.selfKind() === null && K1.c.selfKind() === null, 'selfKind(): desk; an unknown one or none: null');
|
|
416
|
+
ok((() => { try { make(Object.assign(agent('kinds bad'), { selfKind: 'robot' })); return false; } catch (e) { return e instanceof TypeError; } })(), 'selfKind: a string not a kind refused at construction');
|
|
417
|
+
for (const a of [N1, N2, N3, N4, K1, K2, K3, K4]) await a.c.stop();
|
|
407
418
|
for (const a of all) await a.c.stop();
|
|
408
419
|
} finally {
|
|
409
420
|
await relay.close();
|
package/test-relay-lane.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { tmpdir } from 'node:os';
|
|
|
12
12
|
import { dirname, join } from 'node:path';
|
|
13
13
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
14
14
|
import { keygen } from 'sigelo';
|
|
15
|
-
import { CHUNK, LOW, REASONS, checkMessage, readFrame, frames } from './transfer.mjs';
|
|
15
|
+
import { CHUNK, LOW, REASONS, checkMessage, readFrame, frames, manifest } from './transfer.mjs';
|
|
16
16
|
import * as E from './transfer-engine.mjs';
|
|
17
17
|
import { FILE_LABEL, MAX_FILE } from './file.mjs';
|
|
18
18
|
|
|
@@ -132,6 +132,71 @@ const OWN = { did: 'did:sigelo:zOwn', name: 'own', tier: 'own' }, PAL = { did: '
|
|
|
132
132
|
}
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
+
// ================================================================ the accept rule, whatever the lane (2026-11-25)
|
|
136
|
+
// On the phone, with direct off, every file waited for a manual accept. The rule (transfer auto <contact> <MB>)
|
|
137
|
+
// says yes under the size; the direct switch only picks the lane: off, no Tor, the receiver ends no_path at once and the
|
|
138
|
+
// sender's relay lane carries it (up to 8 MiB).
|
|
139
|
+
{
|
|
140
|
+
const io = memIo(), car = fakeCarrier([OWN, PAL, NEW]), x = new E.Engine({ carrier: car, io, compared: (d) => d === PAL.did, timer: false });
|
|
141
|
+
car.takeTransfers = () => { const l = car.inbound ?? []; car.inbound = []; return l; };
|
|
142
|
+
const offer = async (from, size) => {
|
|
143
|
+
const n = Math.ceil(size / CHUNK), m = manifest({ name: 'f.bin', size, sha256: 'ab'.repeat(32), hashes: new Uint8Array(n * 32), now: NOW });
|
|
144
|
+
car.inbound = [{ from: from.did, name: from.name, content: m }];
|
|
145
|
+
await x.round();
|
|
146
|
+
return E.list({ carrier: car, io }).in.find((r) => r.id === m.id);
|
|
147
|
+
};
|
|
148
|
+
E.setDirect({ carrier: car, io, contact: 'own', on: false });
|
|
149
|
+
E.setAuto({ carrier: car, io, contact: 'own', mb: 100 });
|
|
150
|
+
const r1 = await offer(OWN, 3_000_000);
|
|
151
|
+
ok(r1.by === 'rule' && r1.state === 'failed' && r1.reason === 'no_path', `direct off, auto 100 MB, 3 MB: accepted by the rule, no question (${r1.state}${r1.reason ? `: ${r1.reason}` : ''})`);
|
|
152
|
+
ok(car.sent.some((m) => m.content.typ === 'end' && m.content.id === r1.id && m.content.reason === 'no_path') && !car.sent.some((m) => m.content.typ === 'offer' && m.content.id === r1.id),
|
|
153
|
+
'no direct and no Tor here: no_path to the sender at once (its relay lane takes it), no offer with addresses');
|
|
154
|
+
const r12 = await offer(OWN, 12_000_000);
|
|
155
|
+
ok(r12.state === 'asked' && !r12.by, `direct off, no Tor, 12 MB (over the relay lane's 8 MiB): asked, not accepted to fail no_path unseen (${r12.state})`);
|
|
156
|
+
io.tor = { caps: async () => ({ serve: false, connect: false }), close() {} };
|
|
157
|
+
const r13 = await offer(OWN, 13_000_000);
|
|
158
|
+
ok(r13.by === 'rule', `direct off, Tor on here, 13 MB: accepted by the rule (Tor may carry it) (${r13.state})`);
|
|
159
|
+
io.tor = null;
|
|
160
|
+
const r2 = await offer(OWN, 101_000_000);
|
|
161
|
+
ok(r2.state === 'asked' && !r2.by, 'the size cap kept: 101 MB over 100 MB is asked');
|
|
162
|
+
E.setAuto({ carrier: car, io, contact: 'own', mb: 0 });
|
|
163
|
+
ok((await offer(OWN, 10)).state === 'asked', 'auto 0 for the contact: always asked, direct off or not');
|
|
164
|
+
E.setAuto({ carrier: car, io, contact: 'own', mb: null });
|
|
165
|
+
const r3 = await offer(PAL, 1000);
|
|
166
|
+
ok(r3.by === 'rule' && E.list({ carrier: car, io }).direct[PAL.did] === undefined, 'a compared friend, direct never asked: accepted by the rule, the switch left unset (no address shown)');
|
|
167
|
+
E.setAuto({ carrier: car, io, contact: 'new', mb: 100 });
|
|
168
|
+
ok((await offer(NEW, 10)).state === 'asked', 'words not compared: asked, whatever its size');
|
|
169
|
+
// Direct on: the rule's yes is followed by an offer (the direct lane), as before.
|
|
170
|
+
E.setDirect({ carrier: car, io, contact: 'own', on: true });
|
|
171
|
+
const rtc = { peer: async () => ({ offer: async () => 'v=0 fake', close() {} }) };
|
|
172
|
+
const y = new E.Engine({ carrier: car, io, rtc: async () => rtc, stun: [], timer: false });
|
|
173
|
+
car.inbound = [{ from: OWN.did, name: 'own', content: manifest({ name: 'g.bin', size: 10, sha256: 'cd'.repeat(32), hashes: new Uint8Array(32), now: NOW }) }];
|
|
174
|
+
await y.round();
|
|
175
|
+
const r4 = E.list({ carrier: car, io }).in.find((r) => r.name === 'g.bin');
|
|
176
|
+
ok(r4.by === 'rule' && r4.state === 'offering' && car.sent.some((m) => m.content.typ === 'offer' && m.content.id === r4.id), `direct on: the rule's yes, then an offer (${r4.state})`);
|
|
177
|
+
// The rule's yeses add up: the disk must hold every file still coming, and at most 8 a contact (WAIT_CONTACT) come
|
|
178
|
+
// unasked at once; past either, asked (a sender sending more than its 8, or many large ones, cannot fill the disk).
|
|
179
|
+
const offerY = async (name, size) => {
|
|
180
|
+
const n = Math.ceil(size / CHUNK), m = manifest({ name, size, sha256: createHash('sha256').update(name).digest('hex'), hashes: new Uint8Array(n * 32), now: NOW });
|
|
181
|
+
car.inbound = [{ from: OWN.did, name: 'own', content: m }];
|
|
182
|
+
await y.round();
|
|
183
|
+
return E.list({ carrier: car, io }).in.find((r) => r.id === m.id);
|
|
184
|
+
};
|
|
185
|
+
const freeWas = io.free;
|
|
186
|
+
io.free = () => E.FREE_MARGIN + 12_000_000;
|
|
187
|
+
const d1 = await offerY('d1.bin', 5_000_000), d2 = await offerY('d2.bin', 5_000_000), d3 = await offerY('d3.bin', 5_000_000);
|
|
188
|
+
ok(d1.by === 'rule' && d2.by === 'rule' && d3.state === 'asked' && !d3.by,
|
|
189
|
+
`12 MB free, three 5 MB files: two by the rule, the third asked (10 MB promised + 5 > 12) (${[d1, d2, d3].map((r) => r.by ?? r.state)})`);
|
|
190
|
+
io.free = freeWas;
|
|
191
|
+
const many = [];
|
|
192
|
+
for (let i = 0; i < 6; i++) many.push(await offerY(`m${i}.bin`, 10));
|
|
193
|
+
const nRule = [r4, d1, d2, ...many].filter((r) => E.list({ carrier: car, io }).in.find((z) => z.id === r.id)?.by === 'rule').length;
|
|
194
|
+
ok(nRule === 8 && many.at(-1).state === 'asked' && many.slice(0, -1).every((r) => r.by === 'rule'),
|
|
195
|
+
`3 files from one contact already coming, 6 more: 5 by the rule (8 at once), the 6th asked (${many.map((r) => r.by ?? r.state)})`);
|
|
196
|
+
for (const r of [r4, d1, d2, ...many]) y.drop(r.id, 'cancelled');
|
|
197
|
+
await x.close(); await y.close();
|
|
198
|
+
}
|
|
199
|
+
|
|
135
200
|
// ================================================================ two agents on a loopback relay, a fake direct path
|
|
136
201
|
const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', '..', 'relay');
|
|
137
202
|
if (!existsSync(join(RELAY_DIR, 'server.mjs'))) {
|
|
@@ -238,6 +303,16 @@ try {
|
|
|
238
303
|
await sleep(1500);
|
|
239
304
|
ok(aRec(r3.id).state === 'failed' && !aRec(r3.id).relay && !aRec(r3.id).path_used, 'not fallen back to the relay lane');
|
|
240
305
|
ok(await failure(() => A.relay(r3.id, { manual: true })) === 'file_too_large', 'Send over the relay is refused past 8 MiB (the bubble offers Retry)');
|
|
306
|
+
|
|
307
|
+
// 4. Direct off at the receiver (2026-11-25), its rule "transfer auto alice 100": no question, over the relay lane.
|
|
308
|
+
net.blocked = false;
|
|
309
|
+
X.setDirect({ carrier: bob.c, identity: bob.identity, contact: 'alice', on: false });
|
|
310
|
+
X.setAuto({ carrier: bob.c, identity: bob.identity, contact: 'alice', mb: 100 });
|
|
311
|
+
const pdf = seeded('pdf', 2 * CHUNK + 5); writeFileSync(join(dir, 'notes.pdf'), pdf);
|
|
312
|
+
const r4 = await X.send({ carrier: alice.c, identity: alice.identity, to: 'bob', path: join(dir, 'notes.pdf') });
|
|
313
|
+
ok(await until(() => aRec(r4.id)?.state === 'done', 60000) && aRec(r4.id).path_used === 'relay', 'direct off, auto 100 MB: done over the relay lane', JSON.stringify(aRec(r4.id)));
|
|
314
|
+
ok(await until(async () => (await bFile(sha(pdf))) !== undefined, 60000), 'the receiver has it whole, no accept given');
|
|
315
|
+
ok(bRec(r4.id)?.by === 'rule' && !bEv.some((e) => e.what === 'asked' && e.id === r4.id), 'accepted by the rule: never asked', JSON.stringify(bRec(r4.id)));
|
|
241
316
|
} finally {
|
|
242
317
|
await A?.close().catch(() => {}); await B?.close().catch(() => {});
|
|
243
318
|
await alice.c.stop().catch(() => {}); await bob.c.stop().catch(() => {});
|
package/test-transfer-web.mjs
CHANGED
|
@@ -13,10 +13,11 @@ import { tmpdir } from 'node:os';
|
|
|
13
13
|
import { dirname, join } from 'node:path';
|
|
14
14
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
15
15
|
import { keygen } from 'sigelo';
|
|
16
|
-
import { CHUNK, LOW, acceptRule, chunkLength, chunksOf } from './transfer.mjs';
|
|
16
|
+
import { CHUNK, LOW, acceptRule, chunkLength, chunksOf, noPath } from './transfer.mjs';
|
|
17
17
|
import * as E from './transfer-engine.mjs';
|
|
18
18
|
import { webIo, webTransfers } from './transfer-web.mjs';
|
|
19
|
-
import { channelOf, noMdns } from './rtc-web.mjs';
|
|
19
|
+
import { channelOf, iceServers, noMdns, peer as webPeer } from './rtc-web.mjs';
|
|
20
|
+
import * as W from './rtc-web.mjs';
|
|
20
21
|
import { PHOTO_LABEL, PHOTO_MAX, checkPhoto, imageType } from './photo.mjs';
|
|
21
22
|
|
|
22
23
|
let count = 0;
|
|
@@ -86,7 +87,7 @@ export function fakeShell({ landFails = null } = {}) {
|
|
|
86
87
|
ok(t({ size: 25e6 }) === 'auto' && t({ size: 25e6 + 1 }) === 'ask', '25 MB exactly lands; one byte more asks (MB = 10^6)');
|
|
87
88
|
ok(t({ limitMb: 0 }) === 'ask' && t({ limitMb: 2 }) === 'ask' && t({ limitMb: 4 }) === 'auto', 'the contact\'s own size wins: 0 always asks');
|
|
88
89
|
ok(t({ defaultMb: 0 }) === 'ask' && t({ defaultMb: 1, limitMb: 5 }) === 'auto', 'the default 0: always ask, unless the contact has its own');
|
|
89
|
-
ok(t({ direct: null }) === '
|
|
90
|
+
ok(t({ direct: null }) === 'auto' && t({ direct: false }) === 'auto', 'the direct switch is not the rule\'s (2026-11-25): off or not asked, still auto (the lane falls to Tor or the relay)');
|
|
90
91
|
const c = (x) => ({ did: 'did:sigelo:zA', tier: 'friend', ...x });
|
|
91
92
|
ok(E.trustOf(c({ tier: 'own' })) === 'own' && E.trustOf(c({ ours: true })) === 'own', 'trustOf: own tier and ours are own');
|
|
92
93
|
ok(E.trustOf(c({}), () => true) === 'compared' && E.trustOf(c({}), () => false) === 'other', 'trustOf: a friend is known once the words were compared');
|
|
@@ -143,6 +144,50 @@ export function fakeShell({ landFails = null } = {}) {
|
|
|
143
144
|
ok(X.setAuto({ carrier, contact: 'bob', mb: 0 }).auto_mb === 0 && X.list({ carrier }).auto['did:sigelo:zBob'] === 0, 'setAuto: per contact, in the list');
|
|
144
145
|
}
|
|
145
146
|
|
|
147
|
+
// ================================================================ TURN (2026-11-26): the relay's credential at each attempt
|
|
148
|
+
const TURN = { urls: ['turn:relay.test:3478?transport=udp', 'turn:relay.test:3478?transport=tcp'], username: '1764200000:abcdefghijklmnop', credential: 'Y3JlZGVudGlhbA==', exp: 1764200000 };
|
|
149
|
+
{
|
|
150
|
+
ok(JSON.stringify(iceServers(['relay.test:3478'])) === '[{"urls":["stun:relay.test:3478"]}]' && JSON.stringify(iceServers([], null)) === '[]', 'the page\'s ICE servers without TURN: STUN alone, as before');
|
|
151
|
+
ok(JSON.stringify(iceServers(['relay.test:3478'], TURN)) === JSON.stringify([{ urls: ['stun:relay.test:3478'] }, { urls: TURN.urls, username: TURN.username, credential: TURN.credential }]), 'with TURN: the relay\'s turn: URIs, username, credential after STUN');
|
|
152
|
+
let cfg = null;
|
|
153
|
+
class R { constructor(c) { cfg = c; } addEventListener() {} close() {} }
|
|
154
|
+
const p = await webPeer({ stun: ['relay.test:3478'], turn: TURN, RTC: R });
|
|
155
|
+
ok(cfg.iceServers.length === 2 && cfg.iceServers[1].credential === TURN.credential && cfg.iceTransportPolicy === undefined, 'rtc-web peer(): the connection gets STUN and TURN; the policy stays "all" (a direct pair preferred)');
|
|
156
|
+
p.close();
|
|
157
|
+
const eng = (o, carrier) => new E.Engine({ carrier, io: {}, timer: false, ...o });
|
|
158
|
+
const asked = [];
|
|
159
|
+
const c1 = { turnServer: async () => { asked.push(1); return TURN; } };
|
|
160
|
+
ok((await eng({}, c1).turnOf(W))?.username === TURN.username && asked.length === 1, 'the engine asks carrier.turnServer() at each attempt');
|
|
161
|
+
ok(await eng({ turn: false }, c1).turnOf(W) === null && await eng({ env: { SIGELO_TURN: 'off' } }, c1).turnOf(W) === null && asked.length === 1, 'turn: false, or SIGELO_TURN=off: none, nothing asked');
|
|
162
|
+
ok(await eng({}, { turnServer: async () => { throw new Error('down'); } }).turnOf(W) === null && await eng({}, {}).turnOf(W) === null && await eng({}, { turnServer: async () => null }).turnOf(W) === null,
|
|
163
|
+
'a carrier that fails, has no turnServer, or whose relay gives none: null (STUN alone)');
|
|
164
|
+
ok(await eng({}, c1).turnOf({ peer() {} }) === null && await eng({}, c1).turnOf({ TURN_OK: false }) === null && asked.length === 1,
|
|
165
|
+
'a module that does not say TURN_OK true (werift without its handshake checks): no credential asked');
|
|
166
|
+
ok((await eng({}, c1).turnOf(await import('../transfer/rtc.mjs')))?.username === TURN.username && asked.length === 2,
|
|
167
|
+
'werift (apps/transfer/rtc.mjs) with its handshake checks in place: TURN_OK true, a credential asked');
|
|
168
|
+
// "Always relay my media" (design/calls.md §6): the policy, the page's peer under it, the engine's.
|
|
169
|
+
ok(eng({}, {}).policyNow() === 'all' && eng({ policy: () => 'relay' }, {}).policyNow() === 'relay' && eng({ env: { SIGELO_ICE_POLICY: 'relay' } }, {}).policyNow() === 'relay'
|
|
170
|
+
&& eng({ policy: () => { throw new Error('x'); } }, {}).policyNow() === 'all', 'the engine\'s policy: the setting (policy()) or SIGELO_ICE_POLICY=relay; else all');
|
|
171
|
+
ok(await failure(() => webPeer({ stun: ['relay.test:3478'], turn: null, RTC: R, policy: 'relay' })) === 'relay_only', 'rtc-web peer(): relay only without TURN: refused relay_only, no connection made');
|
|
172
|
+
cfg = null;
|
|
173
|
+
class RS { constructor(c) { cfg = c; this.iceGatheringState = 'complete'; this.localDescription = null; } addEventListener() {} createDataChannel() { return { readyState: 'connecting', addEventListener() {} }; }
|
|
174
|
+
async createOffer() { return { type: 'offer', sdp: '' }; } async setLocalDescription() { this.localDescription = { sdp: 'v=0\r\na=candidate:1 1 udp 1 192.0.2.7 5000 typ host\r\na=candidate:3 1 udp 1 198.51.100.4 49200 typ relay raddr 203.0.113.9 rport 6000\r\n' }; }
|
|
175
|
+
async getStats() { return new Map([['t', { id: 't', type: 'transport', selectedCandidatePairId: 'p' }], ['p', { id: 'p', type: 'candidate-pair', localCandidateId: 'l', remoteCandidateId: 'r' }], ['l', { id: 'l', candidateType: 'relay' }], ['r', { id: 'r', candidateType: 'srflx' }]]); } close() {} }
|
|
176
|
+
const pr = await webPeer({ stun: ['relay.test:3478'], turn: TURN, RTC: RS, policy: 'relay' }), o = await pr.offer('sigelo-transfer/0 x 1');
|
|
177
|
+
ok(cfg.iceTransportPolicy === 'relay' && cfg.iceServers.length === 1 && !/192\.0\.2\.7|203\.0\.113\.9/.test(o) && /typ relay raddr 0\.0\.0\.0 rport 0/.test(o),
|
|
178
|
+
'rtc-web peer() relay only: iceTransportPolicy relay, TURN alone, the SDP with the relayed candidate only, raddr zeroed', o);
|
|
179
|
+
ok(await pr.relayed() === true, 'rtc-web relayed(): the selected pair has a relayed candidate (call.mjs relayedOf, as the call screen)');
|
|
180
|
+
pr.close();
|
|
181
|
+
const W2 = await import('../transfer/rtc.mjs');
|
|
182
|
+
ok(await failure(() => W2.peer({ turn: null, policy: 'relay' })) === 'relay_only', 'werift peer(): relay only without TURN: relay_only');
|
|
183
|
+
const wr = await W2.peer({ turn: { ...TURN, urls: ['turn:127.0.0.1:9?transport=udp'] }, gatherMs: 300, policy: 'relay' }), wo = await wr.offer('sigelo-transfer/0 y 1');
|
|
184
|
+
ok(typeof wo === 'string' && !/typ (host|srflx)/.test(wo) && wr.pc.config?.iceTransportPolicy === 'relay', 'werift relay only (a TURN that answers nothing): no host or srflx candidate in the offer', wo);
|
|
185
|
+
ok(await wr.relayed() === null, 'werift relayed(): no pair selected yet: null');
|
|
186
|
+
wr.close();
|
|
187
|
+
ok(noPath('bob').startsWith('No direct path to bob from these two networks') && noPath('bob', true).startsWith('No path to bob from these two networks, not even through the relay host'),
|
|
188
|
+
'no path: the old words without TURN; "not even through the relay host" with it');
|
|
189
|
+
}
|
|
190
|
+
|
|
146
191
|
// ================================================================ a page engine against a Node agent on a loopback relay
|
|
147
192
|
const RELAY_DIR = process.env.SIGELO_RELAY_DIR ?? join(HERE, '..', '..', 'relay');
|
|
148
193
|
if (!existsSync(join(RELAY_DIR, 'server.mjs')) || !existsSync(join(HERE, '..', 'transfer', 'node_modules', 'werift'))) {
|
|
@@ -175,7 +220,15 @@ const pEvents = [], nEvents = [];
|
|
|
175
220
|
const phone = carrierOf('phone', (e) => { if (e.type === 'transfer') P?.e.kick(); });
|
|
176
221
|
const node = carrierOf('node', (e) => { if (e.type === 'transfer') N?.e.kick(); });
|
|
177
222
|
const sh = fakeShell(), pio = webIo({ files: sh.files, big: sh.big }), PX = webTransfers(pio, { rtc });
|
|
178
|
-
|
|
223
|
+
// The page's peers recorded: this loopback relay gives no TURN, so every attempt goes with STUN alone, as before TURN.
|
|
224
|
+
const peers = [], rtcSeen = { ...rtc, peer: (o) => { peers.push(o); return rtc.peer(o); } };
|
|
225
|
+
{
|
|
226
|
+
ok(rtc.TURN_OK === true && JSON.stringify(rtc.iceServers([], TURN)) === JSON.stringify(iceServers([], TURN)), 'sigelo-transfer (werift, handshake checks in place): TURN_OK true, the same ICE servers as the page');
|
|
227
|
+
const w = await rtc.peer({ stun: [], turn: { ...TURN, urls: ['turn:127.0.0.1:9?transport=udp'] }, gatherMs: 200 });
|
|
228
|
+
ok(w.pc && typeof (await w.offer('sigelo-transfer/0 t 1')) === 'string', 'werift takes a TURN server (one that answers nothing: host candidates still offered)');
|
|
229
|
+
w.close();
|
|
230
|
+
}
|
|
231
|
+
P = { ...phone, X: PX, e: new E.Engine({ carrier: phone.c, io: pio, rtc: async () => rtcSeen, stun: [], maxServe: 2, retryMs: 300, onEvent: (e) => pEvents.push(e) }) };
|
|
179
232
|
N = { ...node, e: new X.Engine({ carrier: node.c, identity: node.identity, stun: [], tor: null, retryMs: 300, onEvent: (e) => nEvents.push(e) }) };
|
|
180
233
|
try {
|
|
181
234
|
const inv = await P.c.invite({ name: 'node' });
|
|
@@ -193,6 +246,7 @@ try {
|
|
|
193
246
|
ok(await until(() => nRec('in', r1.id)?.state === 'done', 120000), 'phone → computer, own contact, 3 MB: landed by the rule', JSON.stringify(nRec('in', r1.id)));
|
|
194
247
|
ok(sha(readFileSync(nRec('in', r1.id).saved)) === sha(shot) && nRec('in', r1.id).path_used === 'direct', 'whole, over the direct path (the page\'s engine, werift in this test)');
|
|
195
248
|
ok(await until(() => pRec('out', r1.id)?.state === 'done'), 'the phone\'s record: done');
|
|
249
|
+
ok(nRec('in', r1.id).relayed === false && pRec('out', r1.id).relayed === false, 'both records: relayed false (the selected pair is direct: the transfers list says "direct")', JSON.stringify([nRec('in', r1.id).relayed, pRec('out', r1.id).relayed]));
|
|
196
250
|
ok(sh.big.ops.filter((x) => x === 'read').length === 4, `read by range, one per chunk (${sh.big.ops.filter((x) => x === 'read').length})`);
|
|
197
251
|
|
|
198
252
|
// Computer → phone: 6 MB; it lands in Downloads through the shell; the bitmap saved after every chunk.
|
|
@@ -236,11 +290,24 @@ try {
|
|
|
236
290
|
sh.big.docs.get(d5.doc).mtime = 2000;
|
|
237
291
|
X.accept({ carrier: N.c, identity: N.identity, id: r5.id }); N.e.kick();
|
|
238
292
|
ok(await until(() => pRec('out', r5.id)?.reason === 'file_changed' && nRec('in', r5.id)?.reason === 'file_changed'), 'the picked file changed after the offer: file_changed both sides');
|
|
293
|
+
|
|
294
|
+
// "Always relay my media" on the phone, and this relay offers no TURN: its direct lane left out at once, no peer made
|
|
295
|
+
// (nothing gathered), the record says the sentence; the sender is told no_path (its relay lane or Tor, as ever).
|
|
296
|
+
X.settings({ identity: N.identity, patch: { auto_mb: 25 } });
|
|
297
|
+
P.e.policy = () => 'relay';
|
|
298
|
+
const n0 = peers.length, ro = seeded('relayonly', 2000); writeFileSync(join(dir, 'ro.bin'), ro);
|
|
299
|
+
const r6 = await X.send({ carrier: N.c, identity: N.identity, to: 'phone', path: join(dir, 'ro.bin') });
|
|
300
|
+
ok(await until(() => pRec('in', r6.id)?.reason === 'relay_only' || pRec('in', r6.id)?.state === 'relayed', 60000) && peers.length === n0,
|
|
301
|
+
'relay only, no TURN: no peer made on the phone; failed relay_only (or relayed by the sender\'s relay lane)', JSON.stringify(pRec('in', r6.id)));
|
|
302
|
+
ok(pEvents.some((e) => e.what === 'no_direct' && e.id === r6.id && e.detail === E.RELAY_ONLY), `the phone's event says "${E.RELAY_ONLY}"`);
|
|
303
|
+
ok(await until(() => ['failed', 'relaying', 'done'].includes(nRec('out', r6.id)?.state), 60000) && nRec('out', r6.id)?.path_used !== 'direct', 'the sender told: not over the direct lane', JSON.stringify(nRec('out', r6.id)));
|
|
304
|
+
P.e.policy = () => 'all';
|
|
239
305
|
} finally {
|
|
240
306
|
await P.e.close().catch(() => {}); await N.e.close().catch(() => {});
|
|
241
307
|
await P.c.stop().catch(() => {}); await N.c.stop().catch(() => {});
|
|
242
308
|
await relay.close();
|
|
243
309
|
rmSync(dir, { recursive: true, force: true });
|
|
244
310
|
}
|
|
311
|
+
ok(peers.length > 0 && peers.every((o) => o.turn === null), `the relay gives no TURN: every attempt with STUN alone (${peers.length} peers)`);
|
|
245
312
|
report();
|
|
246
313
|
console.log(`ALL PASS (${count})`);
|