sigelo-contact 0.1.13 → 0.1.20
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 +13 -10
- package/call.mjs +727 -0
- package/carrier.mjs +1204 -137
- package/control.mjs +81 -22
- package/device.mjs +1 -1
- package/enrol.mjs +239 -43
- package/gen-carrier.mjs +4 -4
- package/gen-device.mjs +2 -2
- package/gen-envelope.mjs +3 -3
- package/gen-invite.mjs +3 -3
- package/gen-short.mjs +3 -3
- package/group.mjs +616 -0
- package/invite.mjs +63 -13
- package/kdf.mjs +1 -1
- package/link.mjs +24 -16
- package/package.json +49 -7
- package/page.mjs +1172 -70
- package/photo.mjs +37 -0
- package/platform-node.mjs +125 -18
- package/prekeys.mjs +10 -2
- package/public.mjs +93 -0
- package/relays.mjs +1 -1
- package/restore.mjs +3 -3
- package/rtc-web.mjs +95 -0
- package/short.mjs +31 -3
- package/store.mjs +147 -12
- package/test-carrier.mjs +138 -21
- package/test-device.mjs +1 -1
- package/test-enrol.mjs +157 -8
- package/test-envelope.mjs +16 -3
- package/test-file.mjs +5 -5
- package/test-group.mjs +413 -0
- package/test-invite.mjs +15 -2
- package/test-link.mjs +11 -8
- package/test-platform.mjs +5 -5
- package/test-presence.mjs +169 -0
- package/test-push.mjs +136 -0
- package/test-relay-lane.mjs +248 -0
- package/test-short.mjs +38 -12
- package/test-tier.mjs +6 -6
- package/test-transfer-web.mjs +246 -0
- package/test-transfer.mjs +463 -0
- package/test-voice.mjs +158 -0
- package/test-ws.mjs +5 -5
- package/transfer-engine.mjs +800 -0
- package/transfer-node.mjs +449 -0
- package/transfer-web.mjs +80 -0
- package/transfer.mjs +388 -0
- package/voice-web.mjs +113 -0
- package/voice.mjs +65 -0
- package/words-lock.mjs +115 -0
package/page.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
// The page's routes over one carrier (
|
|
3
|
-
// (
|
|
2
|
+
// The page's routes over one carrier (apps/agent/UI-API.md), shared by `sigelo-agent ui`
|
|
3
|
+
// (apps/agent/sigelo-agent-ui.ts: HTTP on 127.0.0.1) and the self-contained app (apps/web/router.mjs:
|
|
4
4
|
// in the page). One route table, one JSON: what is the same everywhere is here; what one host has
|
|
5
5
|
// and the other has not (the agents' directory, devices, the seat, the HTTP and LAN listeners)
|
|
6
6
|
// comes in as hooks or as routes the host adds.
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
// await p.start(), await p.halt() timers, the carrier's session, the first drain; halt: timers off, links done (then carrier.stop())
|
|
13
13
|
// p.serial(fn), p.refuse(status, check, message), p.contactOf(did), p.cleanName(v, what), p.record(r), p.seen(did),
|
|
14
14
|
// p.data, p.saveData(), p.live, p.recs, p.onChange(fn) for the host's own routes and its banners
|
|
15
|
+
// p.line the calls' Line (call.mjs): the host's Hang up from outside the page (a notification)
|
|
15
16
|
//
|
|
16
17
|
// store: the page's two files, the host's way: readHistory() → text | null, append(line) (a JSON
|
|
17
18
|
// line and "\n"), clearHistory(), readData() → text | null, writeData(text). The history is every
|
|
@@ -25,6 +26,12 @@
|
|
|
25
26
|
// confirm(name, match) → whether one was pending } (relay controls whose four words wait: the
|
|
26
27
|
// Controls card; routes in no remote scope, so never asked over the relay or the LAN).
|
|
27
28
|
//
|
|
29
|
+
// Groups (apps/agent/GROUPS.md, design/groups.md §5): groups: group.mjs (the module) and groupsFile
|
|
30
|
+
// (groupsPath of the identity). Each drain hands the carrier's group messages to group.mjs handle(), here
|
|
31
|
+
// in code: without it the page never takes a roster, carries a copy on or files a message. The page's
|
|
32
|
+
// own marks in data: gread (gid → the newest item shown: {mid, at}), gnotices (a stranger added, the
|
|
33
|
+
// creator gone, a refusal: until dismissed). /api/groups/* (UI-API.md "Groups").
|
|
34
|
+
//
|
|
28
35
|
// Agents (ENROL.md, the app's main list): hooks.keeper, where the host has the operator's keeper root:
|
|
29
36
|
// { read() → the keeper file as JSON (workers, …) | null, root(k) → { K, recovery } (K zeroed after use),
|
|
30
37
|
// update(fn) → fn(keeper) applied and kept }. enrolFile: the pending enrolments (enrol.mjs enrolPath). The
|
|
@@ -32,7 +39,82 @@
|
|
|
32
39
|
// `sigelo-agent enrol --name`, which refuses busy beside a page), takes the requests that come through
|
|
33
40
|
// it (kept apart from the devices'), answers them with the worker's identity and files the worker
|
|
34
41
|
// when it pairs (complete). Worker indices are allocated at the seat only (DEVICES.md): a page whose
|
|
35
|
-
// seat is on another device refuses seat_elsewhere.
|
|
42
|
+
// seat is on another device refuses seat_elsewhere. No four words to tap: a worker that pairs as the DID
|
|
43
|
+
// derived from K (enrol.mjs `verified`) is words-checked here at once; the words stay to see, and the
|
|
44
|
+
// optional switch (`confirm_words`) holds the key until "They match" (POST /api/agents/enrol-words).
|
|
45
|
+
//
|
|
46
|
+
// Keeper (UI-API.md "Keeper"): hooks.computer, where this profile is paired to a computer that runs the keeper:
|
|
47
|
+
// { name() → its name, call(method, path, body?) → { status, body } }. /api/keeper* go there; a limit is a
|
|
48
|
+
// policy-change signed here with this identity (the computer relays it, POST /api/keeper/policy). None: elsewhere.
|
|
49
|
+
//
|
|
50
|
+
// Transfers (apps/agent/TRANSFER.md, design/transfer.md §10): hooks.transfers, where the host moves big
|
|
51
|
+
// files ({ lib, identity, make(carrier, onEvent, { compared }) → its Engine; lib: transfer-node.mjs on a
|
|
52
|
+
// computer (a file by its path), transfer-web.mjs's in the phone app (a file picked: doc), which also gives
|
|
53
|
+
// pick(), photo({ keepLocation }), open(saved) and url(doc) }): the page owns the session, so its engine
|
|
54
|
+
// answers offers and moves the bytes; the /api/transfers* routes; none without the hook (404 route).
|
|
55
|
+
// compared(did): the contact's four words were compared here (the accept rule). A photo (PHOTO_LABEL,
|
|
56
|
+
// photo.mjs): its preview goes as one message (a group's: the msg's photo) beside the manifest; the chat
|
|
57
|
+
// shows it at once, then the full file by the transfer whose manifest has its sha256. A voice message (VOICE_LABEL,
|
|
58
|
+
// voice.mjs) goes the same way, its fields as the message and the recording as the file, where the host records
|
|
59
|
+
// (hooks.transfers.rec: write(rec, offset, bytes), keep(rec, name) → { doc } | { path }, read(saved) → bytes).
|
|
60
|
+
//
|
|
61
|
+
// Calls (UI-API.md "Calls", design/calls.md, call.mjs): one Line over this carrier, always; the media is the page's (ui.js's
|
|
62
|
+
// Phone), which reaches it by /api/calls*. hooks.calls, where the host has a shell: { alert({on, id, did, name}) the ring
|
|
63
|
+
// (the phone app: ringtone, vibration, a heads-up; the seam the push build wires to a full-screen ring), audio({on, id,
|
|
64
|
+
// name}) the call's audio mode (CallService), speaker(on), mic(), micSettings() }. "Can call me" (decision 2026-11-17):
|
|
65
|
+
// data.calls[did] true | false, else the default: off for a quiet contact, else data.settings.calls (default on).
|
|
66
|
+
// A call's chat line is a history record { kind: in | out, label CALL_LABEL, text "Call · 3:12" | "Missed call" | …,
|
|
67
|
+
// call: { id, state, secs } }; only a missed one counts as unread (a call taken or made here was seen).
|
|
68
|
+
//
|
|
69
|
+
// Proof of work (design/profiles.md §6): what the human starts here (the page's start, a code, an
|
|
70
|
+
// answer, "Try now") passes the carrier's `started: 'user'`; past the day's three the route answers
|
|
71
|
+
// 409 pow_confirm, and the same call with `pow_confirmed: true` goes on. The carrier's automatic
|
|
72
|
+
// retries stay capped: state's me.pow_capped {relay, next} says when the next one is.
|
|
73
|
+
//
|
|
74
|
+
// Seen receipts (UI-API.md "Seen receipts", carrier.mjs's header): a message of mine is `seen` once the contact's
|
|
75
|
+
// newest receipt (contacts' seen_upto) is at or after the time I sent it. A contact's messages shown (GET /api/messages)
|
|
76
|
+
// send one receipt, the newest iat shown, unless data.settings.seen is false: to a contact that sent one (it reads
|
|
77
|
+
// them), or a first one to a contact not known to (an earlier version takes it as a message once, then hears no more;
|
|
78
|
+
// never to my own agents, which read none);
|
|
79
|
+
// the first receipt from a contact is answered once (a 0 when receipts are off), so both sides know. data.seen: each
|
|
80
|
+
// contact's {sent, told}. Chat defaults (data.settings): new_tier and new_presence, given to a contact at its pairing;
|
|
81
|
+
// notify (all chats) and data.notify (a chat: contact DID or gid → false) for the notifications.
|
|
82
|
+
//
|
|
83
|
+
// The Wallet settings (UI-API.md "Wallet", design/ux1/notes.md "Decided"): per profile, in data.settings: wallet (the
|
|
84
|
+
// switch, default off), prices (a local price, opt-in, default off) and currency (one of CURRENCIES). Read in state's
|
|
85
|
+
// me.wallet by every form of the page. This page holds no wallet: GET /api/wallet answers where: "none", its other
|
|
86
|
+
// wallet routes 409 wallet_none ("This phone has no wallet yet"); `sigelo-agent ui` answers them with the computer's.
|
|
87
|
+
//
|
|
88
|
+
// Pictures (UI-API.md "Pictures", design/ux1/notes.md "Decided"): store.readPicture(name) → bytes | null and
|
|
89
|
+
// store.writePicture(name, bytes | null), the host's (beside the page's data, 0600, on a computer; the profile's storage
|
|
90
|
+
// on the phone). data.pics: key → {type, rev, at} for 'me' (this identity's own), 'l:<did or gid>' (a local one for a
|
|
91
|
+
// contact or a group: wins) and 't:<did>' (the one a contact sent). Mine travels as one more body inside the
|
|
92
|
+
// end-to-end envelope (label PICTURE_LABEL: {type, data} or {remove: true}), never to the relay in the clear, and only to
|
|
93
|
+
// a contact known to read it: its seen receipt came (seen_peer) or its own picture did (data.pic_peer). An earlier
|
|
94
|
+
// version never gets one; data.pic_sent: what each contact has. A received one is checked (JPEG or WebP, at most
|
|
95
|
+
// PICTURE_MAX bytes), kept as t:<did>, never in the history.
|
|
96
|
+
//
|
|
97
|
+
// Signed statements (UI-API.md "Signed statements"): a text signed with this identity's key, portable: the text, a line
|
|
98
|
+
// naming the signer's four words, and `sigelo-statement/0 <base64url of JCS {body, sig, bundle}>`; body {v, typ:
|
|
99
|
+
// "statement", did (the signing key's DID), iat, text}, sig over "sigelo\n" ‖ JCS(body) (SPEC §3), bundle the chain only
|
|
100
|
+
// (genesis and rotations: no attestation, binding or issuer travels with it). Checked offline against that bundle
|
|
101
|
+
// (SPEC §9): the chain, the DID in it, the signature. In a chat: a message labelled STATEMENT_LABEL whose text is the
|
|
102
|
+
// portable form (an earlier version shows the text as it is). No protocol object: a chat-layer body.
|
|
103
|
+
//
|
|
104
|
+
// A hosted agent's approval and question (apps/agent sigelo-agent-host.ts "Approvals"): APPROVAL_LABEL {code, tool,
|
|
105
|
+
// summary, exp, text}, QUESTION_LABEL {question, options?, text}; checked (promptOf), kept as `approval` / `question`
|
|
106
|
+
// beside a one-line text; the page's buttons answer with a reply's text (`yes CODE`, an option). Malformed: shown as data.
|
|
107
|
+
//
|
|
108
|
+
// The public invite (UI-API.md "Public invite"): a public code (sigelo-public/0, carrier.mjs invitePublic), PUB-…
|
|
109
|
+
// 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
|
+
// approve (/api/public/approve, /refuse) unless open; Pause and the cap: /api/public/set; Stop for good (Revoke for
|
|
111
|
+
// all): /api/invite/cancel {id}. An earlier version's 7-day long code (data.public) runs out as an ordinary invite.
|
|
112
|
+
//
|
|
113
|
+
// Codes that renew themselves (UI-API.md "Renewing codes"): POST /api/invite renew, a short person code that the
|
|
114
|
+
// carrier replaces with a fresh one once it is used (store.mjs renew, in the contact store). Its id here is "r" + the
|
|
115
|
+
// series id, the same after a restart; state's pending invite is the current code, `renew: true`, `used` the codes
|
|
116
|
+
// used. Cancel (/api/invite/cancel, an id or a short code) cancels at the relay too (carrier.mjs cancelInvite) and
|
|
117
|
+
// ends the series.
|
|
36
118
|
//
|
|
37
119
|
// The relay setting (UI-API.md "Settings"): the relay new codes name, kept in data.settings.relay.
|
|
38
120
|
// Precedence: relayFixed (the host's environment: SIGELO_RELAY, or a relay the host was given) wins,
|
|
@@ -40,20 +122,142 @@
|
|
|
40
122
|
// once to new codes (invite names it) and becomes the carrier's own relay at the next start. Codes
|
|
41
123
|
// to accept never read it: a 12-character code names its relay by its tag, an 8-character one is
|
|
42
124
|
// relay.sigelo.ai's (the carrier's relayForShort).
|
|
43
|
-
import {
|
|
44
|
-
import {
|
|
125
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
126
|
+
import { bytesToHex, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
127
|
+
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';
|
|
130
|
+
import { signAs } from './kdf.mjs';
|
|
45
131
|
import * as E from './enrol.mjs';
|
|
46
132
|
import { checkRelay } from './invite.mjs';
|
|
133
|
+
import { didWords } from './short.mjs';
|
|
134
|
+
import { FILE_LABEL } from './file.mjs';
|
|
135
|
+
import { PHOTO_LABEL, checkPhoto } from './photo.mjs';
|
|
136
|
+
import { VOICE_LABEL, VOICE_SIZE_MAX, checkVoice } from './voice.mjs';
|
|
137
|
+
|
|
138
|
+
// The tiers a new contact may be given at its pairing (Settings → Chats: new people's messages).
|
|
139
|
+
const TIER_NEW = new Set(['own', 'friend', 'quiet']);
|
|
140
|
+
export const CURRENCIES = ['EUR', 'USD', 'GBP', 'CHF', 'RON', 'JPY', 'CAD', 'AUD', 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'BRL', 'INR'];
|
|
47
141
|
|
|
48
142
|
const DAY = 86400, TAG_MAX = 20, NAME_MAX = 64, TEXT_MAX = 100_000;
|
|
49
143
|
// An agent's name: a contact name and, placed here, a file name (sigelo.<name>.local.json), as `enrol --name` takes it.
|
|
50
144
|
const AGENT_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
51
145
|
const goodRelay = (h) => { try { checkRelay(h); return true; } catch { return false; } };
|
|
52
146
|
const nowS = () => Math.floor(Date.now() / 1000);
|
|
147
|
+
/** The limits a policy-change sets (apps/keeper/policychange.ts SETTABLE). */
|
|
148
|
+
const KEEPER_FIELDS = ['per_tx_max', 'per_period_max', 'period_seconds', 'rate_per_minute', 'approval_above', 'max_delegates', 'allow', 'paused'];
|
|
53
149
|
const hexOf = (n) => bytesToHex(randomBytes(n));
|
|
150
|
+
// A short change mark of a string (FNV-1a, 32 bits): not a check of anything, only "something changed".
|
|
151
|
+
const hashOf = (t) => { let x = 0x811c9dc5; for (let i = 0; i < t.length; i++) { x ^= t.charCodeAt(i); x = Math.imul(x, 0x01000193) >>> 0; } return x.toString(36); };
|
|
54
152
|
export const refuse = (status, check, message) => { throw Object.assign(new Error(message), { check, status }); };
|
|
55
153
|
|
|
56
|
-
|
|
154
|
+
// ---- pictures and signed statements (the header's)
|
|
155
|
+
export const PICTURE_LABEL = 'sigelo-picture/0', STATEMENT_LABEL = 'sigelo-statement/0', PICTURE_MAX = 64 * 1024, STATEMENT_MAX = 10_000;
|
|
156
|
+
const PICTURE_TYPES = new Set(['image/jpeg', 'image/webp']);
|
|
157
|
+
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
|
+
const unb64 = (t) => Uint8Array.from(atob(t), (c) => c.charCodeAt(0));
|
|
159
|
+
const b64url = (bytes) => b64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
160
|
+
const unb64url = (t) => unb64(t.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (t.length % 4)) % 4));
|
|
161
|
+
/** A picture as it comes (POST /api/picture, a contact's body): its bytes, or a refusal (400 picture). */
|
|
162
|
+
export function pictureBytes(type, data) {
|
|
163
|
+
if (!PICTURE_TYPES.has(type)) refuse(400, 'picture', 'type: image/jpeg or image/webp');
|
|
164
|
+
if (typeof data !== 'string' || data.length > Math.ceil(PICTURE_MAX / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) refuse(400, 'picture', `data: base64 of at most ${PICTURE_MAX / 1024} KB`);
|
|
165
|
+
const b = unb64(data);
|
|
166
|
+
if (b.length === 0 || b.length > PICTURE_MAX) refuse(400, 'picture', `a picture of at most ${PICTURE_MAX / 1024} KB (256 pixels is plenty)`);
|
|
167
|
+
const jpeg = b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff, webp = b.length > 12 && String.fromCharCode(...b.subarray(0, 4)) === 'RIFF' && String.fromCharCode(...b.subarray(8, 12)) === 'WEBP';
|
|
168
|
+
if ((type === 'image/jpeg' && !jpeg) || (type === 'image/webp' && !webp)) refuse(400, 'picture', `not a ${type === 'image/jpeg' ? 'JPEG' : 'WebP'} picture`);
|
|
169
|
+
return b;
|
|
170
|
+
}
|
|
171
|
+
export const APPROVAL_LABEL = 'sigelo-approval/0', QUESTION_LABEL = 'sigelo-question/0';
|
|
172
|
+
/** A received approval or question's content: {key, value, text} (value checked, text its one line), or null (not one, or malformed). */
|
|
173
|
+
export function promptOf(label, c) {
|
|
174
|
+
if (typeof c !== 'object' || c === null || Array.isArray(c)) return null;
|
|
175
|
+
const str = (v, max) => typeof v === 'string' && v.length <= max, one = (v) => v.replace(/\s+/g, ' ').trim();
|
|
176
|
+
if (label === APPROVAL_LABEL) {
|
|
177
|
+
if (!str(c.code, 4) || !/^[A-Za-z0-9]{4}$/.test(c.code) || !str(c.tool, 200) || !str(c.summary, 1000) || !Number.isSafeInteger(c.exp)) return null;
|
|
178
|
+
const value = { code: c.code.toUpperCase(), tool: one(c.tool), summary: one(c.summary), exp: c.exp };
|
|
179
|
+
return { key: 'approval', value, text: `approval ${value.code}: ${value.tool}: ${value.summary} (yes ${value.code} / no ${value.code})` };
|
|
180
|
+
}
|
|
181
|
+
if (label === QUESTION_LABEL) {
|
|
182
|
+
if (!str(c.question, 4000) || (c.options !== undefined && (!Array.isArray(c.options) || c.options.length > 20 || !c.options.every((o) => str(o, 200) && o.trim() !== '')))) return null;
|
|
183
|
+
const value = { question: c.question, ...(c.options?.length && { options: c.options }) };
|
|
184
|
+
return { key: 'question', value, text: `question: ${c.question}${value.options ? `\n${value.options.map((o, i) => ` ${i + 1}) ${o}`).join('\n')}` : ''}` };
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
const chainOnly = (b) => ({ v: 'sigelo/0', typ: 'bundle', genesis: b.genesis, rotations: b.rotations ?? [], bindings: [], attestations: [], issuers: [] });
|
|
189
|
+
const SIGNED_LINE = /\n-- Signed with sigelo by [a-z]+ [a-z]+ [a-z]+ [a-z]+\. Check it in the sigelo app\.\s*$/;
|
|
190
|
+
/** A statement signed now by identity id ({sign | secret, bundle}, the carrier's): → its portable text. */
|
|
191
|
+
export function signStatement(id, text, now) {
|
|
192
|
+
if (typeof text !== 'string' || text.trim() === '' || text.length > STATEMENT_MAX) refuse(400, 'body', `text: 1 to ${STATEMENT_MAX} characters`);
|
|
193
|
+
const bundle = chainOnly(id.bundle), r = verify(bundle, now);
|
|
194
|
+
const body = { v: STATEMENT_LABEL, typ: 'statement', did: r.did, iat: now, text: text.trim() };
|
|
195
|
+
const blob = { body, sig: signAs(id, body), bundle };
|
|
196
|
+
return `${body.text}\n-- Signed with sigelo by ${didWords(r.chain[0])}. Check it in the sigelo app.\n${STATEMENT_LABEL} ${b64url(utf8ToBytes(canonicalize(blob)))}`;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* A statement's portable text checked offline (SPEC §9 on its bundle, then the signature by the key of the DID it names):
|
|
200
|
+
* → {valid: true, text, iat, did, original, chain, current, created, edited} or {valid: false, check, message}. edited: the
|
|
201
|
+
* text shown above the signature differs from the one signed (the signed one is what counts).
|
|
202
|
+
*/
|
|
203
|
+
export function checkStatement(portable, now) {
|
|
204
|
+
const no = (check, message) => ({ valid: false, check, message });
|
|
205
|
+
const t = String(portable ?? '').replace(/\r\n?/g, '\n');
|
|
206
|
+
const m = /(?:^|\n)sigelo-statement\/0\s+([A-Za-z0-9_\-\s]+?)\s*$/.exec(t);
|
|
207
|
+
if (!m) return no('statement_format', 'No sigelo signature in this text: paste all of it, the last line too.');
|
|
208
|
+
let blob;
|
|
209
|
+
try { blob = parseBytes(unb64url(m[1].replace(/\s+/g, ''))); } catch { return no('statement_format', 'The signature line is cut or changed: paste all of it.'); }
|
|
210
|
+
const keys = (o) => (o && typeof o === 'object' && !Array.isArray(o) ? Object.keys(o).sort().join() : '');
|
|
211
|
+
const { body, sig, bundle } = blob ?? {};
|
|
212
|
+
if (keys(blob) !== 'body,bundle,sig' || keys(body) !== 'did,iat,text,typ,v' || body.v !== STATEMENT_LABEL || body.typ !== 'statement' || typeof body.did !== 'string'
|
|
213
|
+
|| !Number.isSafeInteger(body.iat) || body.iat < 0 || typeof body.text !== 'string' || body.text.length > STATEMENT_MAX || typeof sig !== 'string') {
|
|
214
|
+
return no('statement_format', 'Not a sigelo signed message.');
|
|
215
|
+
}
|
|
216
|
+
let r;
|
|
217
|
+
try { r = verify(bundle, now); } catch (e) { return no('statement_identity', `The identity it carries does not verify (${e.message}).`); }
|
|
218
|
+
const g = [bundle.genesis, ...bundle.rotations.map((x) => x.next_genesis)].find((x) => { try { return didOf(x) === body.did; } catch { return false; } });
|
|
219
|
+
if (!g || !r.chain.includes(body.did)) return no('statement_identity', 'The key that signed it is not in the identity it carries.');
|
|
220
|
+
if (!verifySig(g.key, body, sig)) return no('statement_sig', 'The text or its signature was changed after it was signed.');
|
|
221
|
+
if (body.iat > now + 300) return no('statement_time', 'It says it was signed in the future: the signer\'s clock is wrong, or it was changed.');
|
|
222
|
+
const shown = t.slice(0, m.index).replace(SIGNED_LINE, '').trim();
|
|
223
|
+
return { valid: true, text: body.text, iat: body.iat, did: body.did, original: r.chain[0], chain: r.chain, current: r.did === body.did, created: bundle.genesis.created ?? null,
|
|
224
|
+
edited: shown !== '' && shown !== body.text.trim() };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ---- search (UI-API.md "Search"): a substring of the texts this device holds, case and accents folded. Each code point is
|
|
228
|
+
// folded alone (NFD, marks dropped, lower case) so that a hit in the folded text maps back to the text as written: at[i]
|
|
229
|
+
// is where the folded character i came from (at[f.length]: the end).
|
|
230
|
+
/** t folded for search → { f, at }. */
|
|
231
|
+
export function foldMap(t) {
|
|
232
|
+
let f = '';
|
|
233
|
+
const at = [];
|
|
234
|
+
for (let i = 0; i < t.length;) {
|
|
235
|
+
const cp = t.codePointAt(i), x = String.fromCodePoint(cp).normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
|
|
236
|
+
for (let k = 0; k < x.length; k++) at.push(i);
|
|
237
|
+
f += x; i += cp > 0xffff ? 2 : 1;
|
|
238
|
+
}
|
|
239
|
+
at.push(t.length);
|
|
240
|
+
return { f, at };
|
|
241
|
+
}
|
|
242
|
+
export const SNIPPET_MAX = 120;
|
|
243
|
+
/**
|
|
244
|
+
* The first hit of want (folded already) in t → { snippet, mark: [from, to] } or null: at most SNIPPET_MAX characters
|
|
245
|
+
* around the hit (… where cut, line breaks as spaces), mark the hit's place in the snippet (cut at its end if long).
|
|
246
|
+
*/
|
|
247
|
+
export function matchIn(t, want) {
|
|
248
|
+
const { f, at } = foldMap(t), i = f.indexOf(want);
|
|
249
|
+
if (i < 0 || want === '') return null;
|
|
250
|
+
const s = at[i], e = at[i + want.length];
|
|
251
|
+
let from = Math.max(0, Math.min(s - 40, t.length - (SNIPPET_MAX - 1)));
|
|
252
|
+
if (/[\udc00-\udfff]/.test(t[from] ?? '')) from++;
|
|
253
|
+
let to = Math.min(t.length, from + SNIPPET_MAX - (from > 0 ? 1 : 0));
|
|
254
|
+
if (to < t.length) to--;
|
|
255
|
+
if (/[\ud800-\udbff]/.test(t[to - 1] ?? '')) to--;
|
|
256
|
+
const pre = from > 0 ? '…' : '', body = t.slice(from, to).replace(/[\r\n\t]/g, ' ');
|
|
257
|
+
return { snippet: pre + body + (to < t.length ? '…' : ''), mark: [s - from + pre.length, Math.min(e, to) - from + pre.length] };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, groupsFile = null, enrolFile = null, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
|
|
57
261
|
const defer = hooks.defer ?? ((f) => setTimeout(f, 0));
|
|
58
262
|
const every = hooks.every ?? ((f, ms) => { const t = setInterval(f, ms); t.unref?.(); return t; });
|
|
59
263
|
const watchers = new Set();
|
|
@@ -82,17 +286,32 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
82
286
|
};
|
|
83
287
|
let data;
|
|
84
288
|
try { data = JSON.parse(store.readData() ?? 'null') ?? {}; } catch { data = {}; }
|
|
85
|
-
for (const k of ['tags', 'checked', 'read', 'controls', 'settings']) data[k] ??= {};
|
|
289
|
+
for (const k of ['tags', 'checked', 'read', 'controls', 'settings', 'gread', 'seen', 'notify', 'kind', 'pics', 'pic_sent', 'pic_peer']) data[k] ??= {};
|
|
290
|
+
data.gnotices ??= [];
|
|
86
291
|
delete data.waiting; // kept by an earlier page; the carrier says it now (contacts: prekeys, waiting)
|
|
87
292
|
const saveData = () => store.writeData(JSON.stringify(data));
|
|
88
293
|
|
|
89
294
|
// ---- live status, not kept
|
|
90
|
-
const live = { online: new Set(), pow: null, powDone: null, error: null, seatGone: null };
|
|
295
|
+
const live = { online: new Set(), pow: null, powDone: null, error: null, seatGone: null, powCapped: null, powConfirm: null };
|
|
296
|
+
// The last login's failure and the day's cap, kept (data.offline) so that the "Not connected" card says why after a restart
|
|
297
|
+
// too; gone once connected. A cap whose next try has passed is not brought back.
|
|
298
|
+
if (typeof data.offline?.error === 'string') live.error = data.offline.error;
|
|
299
|
+
if (Number.isSafeInteger(data.offline?.pow_capped?.next) && data.offline.pow_capped.next > nowS()) live.powCapped = { relay: String(data.offline.pow_capped.relay), next: data.offline.pow_capped.next };
|
|
300
|
+
const keepOffline = () => {
|
|
301
|
+
const was = JSON.stringify(data.offline ?? null), now = live.error === null && live.powCapped === null ? null : { error: live.error, pow_capped: live.powCapped };
|
|
302
|
+
if (JSON.stringify(now) === was) return;
|
|
303
|
+
if (now === null) delete data.offline; else data.offline = now;
|
|
304
|
+
try { saveData(); } catch {}
|
|
305
|
+
};
|
|
306
|
+
// A call the human made: past the day's searches it asks (pow_confirm) unless they said go on.
|
|
307
|
+
const startedBy = (b) => (b?.['pow_confirmed'] === true ? 'confirmed' : 'user');
|
|
91
308
|
// Writes, one at a time. Once the seat went to another device, every write is refused.
|
|
92
309
|
let chain = Promise.resolve();
|
|
93
310
|
const gone = (fn) => () => (live.seatGone !== null ? refuse(409, 'seat_elsewhere', `the seat went to ${live.seatGone}: this page no longer logs in as you`) : fn());
|
|
94
311
|
const serial = (f0) => { const fn = gone(f0); const p = chain.then(fn, fn); chain = p.catch(() => {}); return p; };
|
|
95
312
|
const invites = new Map();
|
|
313
|
+
// An earlier version's public invite (the header's): an ordinary long invite now, until it runs out.
|
|
314
|
+
if (data.public?.id) { invites.set(data.public.id, { ...data.public }); delete data.public; }
|
|
96
315
|
let devices = null;
|
|
97
316
|
// Enrolments this page issued (agents, below): id (the code's nonce) → { id, worker, name, short, code, exp, relay, tier,
|
|
98
317
|
// state: code | words | sending | enrolled | expired | failed, words, temp, did, original, check?, detail? }.
|
|
@@ -101,16 +320,45 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
101
320
|
// What the carrier's inbox() hands over, as every client takes it: messages and the events it
|
|
102
321
|
// keeps (pairings, failures, rotations), into the history. Taken at once after any event, and
|
|
103
322
|
// every minute for what no event announced.
|
|
104
|
-
let draining = null, again = false;
|
|
323
|
+
let draining = null, again = false, drainedOnline = 0; // drainedOnline: when a drain last ended while connected (ms)
|
|
105
324
|
function take(b) {
|
|
106
325
|
// A linked contact's messages carry the link (id, purpose): data, shown beside them.
|
|
107
326
|
for (const m of (L.labelled ? L.labelled(carrier, b.messages) : b.messages)) {
|
|
108
327
|
// Enrolment and device messages carry keys or codes: never in the history (the device rounds take them).
|
|
109
328
|
if (typeof m['label'] === 'string' && unlogged.test(m['label'])) { if (!holdAgent(m)) devices?.hold(m); continue; }
|
|
110
329
|
if (hidden({ did: m['from'], name: m['name'] })) continue;
|
|
330
|
+
// A contact's own picture (the header's "Pictures"): kept apart, never in the history.
|
|
331
|
+
if (m['label'] === PICTURE_LABEL) { takePicture(m); continue; }
|
|
332
|
+
// A photo's preview (photo.mjs): into the chat at once, the full file by its transfer.
|
|
333
|
+
if (m['label'] === PHOTO_LABEL) {
|
|
334
|
+
let ph = null;
|
|
335
|
+
try { ph = checkPhoto(m['content']); } catch (e) { record({ kind: 'event', type: 'dropped', did: m['from'], name: m['name'], code: 'photo', detail: e.message }); continue; }
|
|
336
|
+
record({ kind: 'in', did: m['from'], name: m['name'], text: 'Photo', label: PHOTO_LABEL, photo: ph, ...(Number.isSafeInteger(m['iat']) && { iat: m['iat'] }) });
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
// A voice message (voice.mjs): its bubble at once, the recording by its transfer.
|
|
340
|
+
if (m['label'] === VOICE_LABEL) {
|
|
341
|
+
let vo = null;
|
|
342
|
+
try { vo = checkVoice(m['content']); } catch (e) { record({ kind: 'event', type: 'dropped', did: m['from'], name: m['name'], code: 'voice', detail: e.message }); continue; }
|
|
343
|
+
record({ kind: 'in', did: m['from'], name: m['name'], text: 'Voice message', label: VOICE_LABEL, voice: vo, ...(Number.isSafeInteger(m['iat']) && { iat: m['iat'] }) });
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
111
346
|
const link = m['link'] ? { link: m['link'] } : {};
|
|
112
|
-
|
|
113
|
-
|
|
347
|
+
// iat: the sender's time of it, what a seen receipt names (Seen receipts, above).
|
|
348
|
+
const iat = Number.isSafeInteger(m['iat']) ? { iat: m['iat'] } : {};
|
|
349
|
+
if (m['type'] === 'file') {
|
|
350
|
+
// (0.1.19) The lane it came by, for the bubble: a transfer's (direct, tor), else the relay (sigelo-file/0), which also
|
|
351
|
+
// ends a transfer of the same file from them that is still open here (Engine.superseded: no ghost left active).
|
|
352
|
+
const lane = m['transfer'] ? (m['via'] ?? null) : 'relay';
|
|
353
|
+
if (!m['transfer']) { try { transfers?.engine.superseded?.(m); } catch {} }
|
|
354
|
+
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 }, ...iat, ...link });
|
|
356
|
+
}
|
|
357
|
+
else {
|
|
358
|
+
// A hosted agent's approval or question (promptOf): its fields beside a one-line text, which a reply quotes.
|
|
359
|
+
const pr = promptOf(m['label'], m['content']);
|
|
360
|
+
record({ kind: 'in', did: m['from'], name: m['name'], text: pr ? pr.text : m['content'], label: m['label'], ...(pr && { [pr.key]: pr.value }), ...iat, ...link });
|
|
361
|
+
}
|
|
114
362
|
}
|
|
115
363
|
const named = new Set();
|
|
116
364
|
for (const e of b.events) {
|
|
@@ -118,13 +366,19 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
118
366
|
if (hidden({ did: d, name: e['name'] })) continue;
|
|
119
367
|
switch (e.type) {
|
|
120
368
|
case 'paired': {
|
|
121
|
-
|
|
122
|
-
|
|
369
|
+
// A renewing code stays current (its next code shows in its place): never "paired" itself.
|
|
370
|
+
const inv = e['renew'] ? invites.get(`r${String(e['renew'])}`) : [...invites.values()].find((x) => x.name === e['name'] && !x.paired && !x.renew);
|
|
371
|
+
if (inv && d && !inv.renew) inv.paired = d;
|
|
123
372
|
record({ kind: 'event', type: 'paired', did: d, name: e['name'] });
|
|
373
|
+
if (d) newContact(d, inv);
|
|
124
374
|
break;
|
|
125
375
|
}
|
|
126
376
|
// A refusal of one of my messages (it has an id) is its status, from onEvent.
|
|
127
377
|
case 'refused': if (e['id'] === undefined) record({ kind: 'event', type: 'refused', did: d, name: e['name'], code: e['code'], detail: e['detail'] }); break;
|
|
378
|
+
// A pairing request to a public code of mine (carrier.mjs #onPublic): its words, to approve or refuse.
|
|
379
|
+
case 'public_request':
|
|
380
|
+
record({ kind: 'event', type: 'public_request', did: d, name: e['name'], detail: `a new chat asks to start by your public code (${String(e['words'])})` });
|
|
381
|
+
break;
|
|
128
382
|
case 'pairing_failed': case 're_pair': case 'rotated': case 'dropped':
|
|
129
383
|
if (e.type === 'dropped') named.add(String(e['check']));
|
|
130
384
|
record({ kind: 'event', type: e.type, did: d, name: e['name'], code: e['code'] ?? e['check'], detail: e['detail'] });
|
|
@@ -137,7 +391,7 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
137
391
|
if (draining) { again = true; return draining; }
|
|
138
392
|
draining = (async () => {
|
|
139
393
|
try {
|
|
140
|
-
do { again = false; take(await carrier.inbox({ local: true })); } while (again);
|
|
394
|
+
do { again = false; const t0 = Date.now(), up = live.online.size > 0; take(await carrier.inbox({ local: true })); callRound(); await groupRound(); if (up && live.online.size > 0) drainedOnline = t0; } while (again);
|
|
141
395
|
// Device messages: wiped answers, a standby asking for the seat (it goes, and this page stops logging in as you).
|
|
142
396
|
if (live.seatGone === null && hooks.deviceRound) {
|
|
143
397
|
const r = await hooks.deviceRound();
|
|
@@ -161,12 +415,14 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
161
415
|
return linking;
|
|
162
416
|
};
|
|
163
417
|
const onEvent = (e) => {
|
|
418
|
+
if (e.type === 'transfer') defer(() => void transfers?.engine.kick());
|
|
419
|
+
if (e.type === 'call') { defer(callRound); return; }
|
|
164
420
|
if (e.type === 'link' || e.type === 'paired') defer(() => void linkRound());
|
|
165
421
|
try {
|
|
166
422
|
const d = e['did'] ?? e['from'] ?? e['peer'];
|
|
167
423
|
switch (e.type) {
|
|
168
424
|
case 'sent': case 'queued': case 'refused': {
|
|
169
|
-
if (e['control'] !== undefined) break;
|
|
425
|
+
if (e['control'] !== undefined || e['receipt'] === true) break;
|
|
170
426
|
// Before send returns, its own result says the same: only later ones are recorded.
|
|
171
427
|
const st = e.type, i = e['id'];
|
|
172
428
|
if (i && outById.has(i)) { record({ kind: 'status', id: i, status: st, code: e['code'], detail: e['detail'] }); break; }
|
|
@@ -176,12 +432,27 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
176
432
|
if (st === 'refused' && !i) soon();
|
|
177
433
|
break;
|
|
178
434
|
}
|
|
179
|
-
case 'pow': live.pow = { bits: Number(e['bits']), since: Date.now() }; break;
|
|
435
|
+
case 'pow': live.pow = { bits: Number(e['bits']), m: Number(e['m'] ?? POW_COST.m), t: Number(e['t'] ?? POW_COST.t), since: Date.now() }; break;
|
|
180
436
|
case 'pow_done': live.pow = null; live.powDone = Number(e['ms']); break;
|
|
181
|
-
case 'connected':
|
|
437
|
+
case 'connected':
|
|
438
|
+
live.online.add(String(e['relay'])); live.error = null; void checkClock();
|
|
439
|
+
if (live.powCapped?.relay === e['relay']) live.powCapped = null;
|
|
440
|
+
if (live.powConfirm?.relay === e['relay']) live.powConfirm = null;
|
|
441
|
+
keepOffline();
|
|
442
|
+
break;
|
|
182
443
|
case 'disconnected': live.online.delete(String(e['relay'])); break;
|
|
183
|
-
case 'error':
|
|
184
|
-
|
|
444
|
+
case 'error':
|
|
445
|
+
// A detail that names itself ("proof of work: …", the platform's) is said as it is.
|
|
446
|
+
live.error = /^proof of work: /.test(String(e['detail'])) ? String(e['detail']) : `${e['check']}: ${e['detail']}`;
|
|
447
|
+
// The day's searches spent: when the next automatic try is, and "Try now" (POST /api/pow/try).
|
|
448
|
+
if (e['check'] === 'pow' && Number.isSafeInteger(e['next'])) live.powCapped = { relay: String(e['relay']), next: e['next'] };
|
|
449
|
+
if (e['check'] === 'pow_confirm') live.powConfirm = { relay: String(e['relay']), detail: String(e['detail']).replace(/^pow_confirm: /, '') };
|
|
450
|
+
keepOffline();
|
|
451
|
+
break;
|
|
452
|
+
case 'notice': case 'presence': case 'group_tier': case 'busy': break; // presence, the group tier, a busy mark: the state says it, nothing to take
|
|
453
|
+
case 'seen': defer(() => { receipt(String(e['from']), true); picturesDue(); }); break;
|
|
454
|
+
// A new contact told its name (carrier.mjs "Names"): my groups that list it under the made-up one are sent again.
|
|
455
|
+
case 'named': if (G && groupsFile) defer(() => serial(() => G.refreshNames({ carrier, file: groupsFile, did: String(e['did']) })).catch(() => {})); break; // the contact's receipt: contacts() has it; answered once; it reads pictures
|
|
185
456
|
default: soon();
|
|
186
457
|
}
|
|
187
458
|
} catch (err) { live.error = `history: ${err.message}`; }
|
|
@@ -189,34 +460,165 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
189
460
|
};
|
|
190
461
|
const kept = () => (typeof data.settings.relay === 'string' && goodRelay(data.settings.relay) ? data.settings.relay : null);
|
|
191
462
|
const carrier = makeCarrier(onEvent, kept() !== null ? { relay: kept() } : {});
|
|
463
|
+
// The engine's events: a file offered, done, failed (into the history as events; the view reads GET /api/transfers).
|
|
464
|
+
const onTransfer = (e) => {
|
|
465
|
+
if (['asked', 'done', 'failed', 'declined', 'cancelled'].includes(e.what)) {
|
|
466
|
+
try { record({ kind: 'event', type: 'transfer', what: e.what, id: e.id, did: e.from ?? null, name: e.contact ?? null, code: e.reason ?? null, detail: e.what === 'asked' ? `${e.name} (${e.size} bytes)` : e.path ?? null }); } catch {}
|
|
467
|
+
}
|
|
468
|
+
changed();
|
|
469
|
+
};
|
|
470
|
+
// The accept rule's "words compared": the pairing's words as the human checked them here (Chats → the four words).
|
|
471
|
+
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
|
+
const transfers = hooks.transfers ? { lib: hooks.transfers.lib, engine: hooks.transfers.make(carrier, onTransfer, { compared }) } : null;
|
|
473
|
+
// ---- calls (the header's): the Line, its messages taken from the carrier at each `call` event and each drain.
|
|
474
|
+
data.calls ??= {};
|
|
475
|
+
const liveContact = (d) => carrier.contacts().contacts.find((c) => c.did === d && !c.revoked) ?? null;
|
|
476
|
+
const canCall = (c) => (typeof data.calls[c.did] === 'boolean' ? data.calls[c.did] : c.tier === 'quiet' ? false : data.settings.calls !== false);
|
|
477
|
+
const CH = hooks.calls ?? {};
|
|
478
|
+
const line = new Line({
|
|
479
|
+
send: (to, content) => carrier.send(to, content, { label: CALL_LABEL, internal: CALL_SEND, local: false }),
|
|
480
|
+
contact: liveContact, allowed: canCall, shares: (c) => c.presence === 'allow' || c.presence === 'own', me: () => hooks.me().original,
|
|
481
|
+
line: ({ did, dir, text, call }) => { record({ kind: dir, did, name: liveContact(did)?.name ?? null, text, label: CALL_LABEL, call }); },
|
|
482
|
+
alert: (x) => { try { CH.alert?.(x); } catch {} },
|
|
483
|
+
audio: (x) => { try { void Promise.resolve(CH.audio?.(x)).catch(() => {}); } catch {} },
|
|
484
|
+
changed: () => changed(),
|
|
485
|
+
});
|
|
486
|
+
const callRound = () => { try { for (const m of carrier.takeCalls()) line.receive(m); } catch (err) { live.error = `calls: ${err.message}`; } };
|
|
192
487
|
// The relay new codes name, as the precedence says.
|
|
193
488
|
const newCodes = () => relayFixed ?? kept() ?? DEFAULT_RELAY;
|
|
194
|
-
|
|
489
|
+
// added: the relays taken here by name (Settings → Relay → Another relay), newest first, so that one stays in the list once another is in use.
|
|
490
|
+
const ADDED_MAX = 5;
|
|
491
|
+
const added = () => (Array.isArray(data.settings.relays) ? data.settings.relays.filter((x) => typeof x === 'string' && goodRelay(x)) : []);
|
|
492
|
+
const settings = () => ({ relay: kept() ?? DEFAULT_RELAY, default: DEFAULT_RELAY, fixed: relayFixed, in_use: carrier.relay, added: added() });
|
|
195
493
|
async function checkClock() { try { await carrier.checkClock(); } catch {} }
|
|
196
494
|
const seen = (d) => { let at = null; for (const r of recs) if (r.did === d && (r.kind === 'in' || r.kind === 'event')) at = r.at; return at; };
|
|
495
|
+
// ---- seen receipts and the chat defaults (the header's)
|
|
496
|
+
const receiptsOn = () => data.settings.seen !== false;
|
|
497
|
+
// The newest of a contact's messages shown (their iat), 0 when none.
|
|
498
|
+
const shownUpto = (d) => { let t = 0; const read = data.read[d] ?? 0; for (const r of recs) if (r.kind === 'in' && r.did === d && r.n <= read && Number.isSafeInteger(r.iat) && r.iat > t) t = r.iat; return t; };
|
|
499
|
+
// A receipt to contact d when one is due; answer: the contact's first receipt came (say that this side reads them too).
|
|
500
|
+
function receipt(d, answer = false) {
|
|
501
|
+
try {
|
|
502
|
+
const x = carrier.contacts().contacts.find((c) => c.did === d && !c.revoked);
|
|
503
|
+
// My own agents read none (no app shows them ticks): only once one sent a receipt.
|
|
504
|
+
if (!x || hidden(x) || (x.ours && !x.seen_peer)) return;
|
|
505
|
+
const s = (data.seen[d] ??= { sent: 0, told: false }), upto = receiptsOn() ? shownUpto(d) : 0;
|
|
506
|
+
const due = receiptsOn() && upto > s.sent && (x.seen_peer || !s.told);
|
|
507
|
+
if (!due && !(answer && !s.told)) return;
|
|
508
|
+
if (receiptsOn()) s.sent = Math.max(s.sent, upto);
|
|
509
|
+
s.told = true; saveData();
|
|
510
|
+
void serial(() => carrier.seen(d, upto)).catch(() => {});
|
|
511
|
+
} catch {}
|
|
512
|
+
}
|
|
513
|
+
// A message of mine: seen once the contact's newest receipt is at or after when it went (at: taken before the send).
|
|
514
|
+
const statusOf = (r, upto) => (r.kind === 'out' && r.status === 'sent' && Number.isSafeInteger(upto) && r.at <= upto ? 'seen' : r.status ?? null);
|
|
515
|
+
// A contact just paired: the chat defaults (a tier the human did not choose at accept, presence), and a group code's group.
|
|
516
|
+
function newContact(d, inv) {
|
|
517
|
+
try {
|
|
518
|
+
const x = carrier.contacts().contacts.find((c) => c.did === d && !c.revoked);
|
|
519
|
+
// An introduced contact (link.mjs) keeps the tier its introduction gave; my own agents theirs.
|
|
520
|
+
if (!x || x.link) return;
|
|
521
|
+
const t = data.settings.new_tier;
|
|
522
|
+
if (TIER_NEW.has(t) && t !== x.tier && !x.ours && x.tier_by !== 'owner') carrier.setTier(d, t);
|
|
523
|
+
if (data.settings.new_presence === true && x.presence === 'deny') carrier.setPresence(d, true);
|
|
524
|
+
} catch {}
|
|
525
|
+
if (inv?.group && G && groupsFile) {
|
|
526
|
+
const gid = inv.group;
|
|
527
|
+
defer(() => void serial(() => G.add({ carrier, file: groupsFile, group: gid, members: [d], humans: [d] })).then(() => changed(), (err) => { gnote({ type: 'group', why: 'refused', check: err.check ?? 'group', count: 1 }); saveData(); changed(); }));
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
const notifyOf = (chat) => data.notify[chat] !== false;
|
|
531
|
+
// The public invite as the state shows it (carrier.mjs publicView): the first public code of mine, or null.
|
|
532
|
+
const publicInvite = (c) => c.publics?.[0] ?? null;
|
|
533
|
+
const walletSet = () => ({ wallet: data.settings.wallet === true, prices: data.settings.prices === true, currency: CURRENCIES.includes(data.settings.currency) ? data.settings.currency : null });
|
|
534
|
+
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, ...walletSet() });
|
|
536
|
+
|
|
537
|
+
// ---- pictures (the header's): mine to the contacts that read them, theirs kept, a local one beside
|
|
538
|
+
const picFile = (key) => (key === 'me' ? 'me' : `${key[0]}-${bytesToHex(sha256(utf8ToBytes(key.slice(2)))).slice(0, 16)}`);
|
|
539
|
+
const picRev = (key) => data.pics[key]?.rev ?? null;
|
|
540
|
+
const picOf = (id) => (id === 'me' ? 'me' : data.pics[`l:${id}`] ? `l:${id}` : data.pics[`t:${id}`] ? `t:${id}` : null);
|
|
541
|
+
const picSave = (key, type, bytes) => {
|
|
542
|
+
store.writePicture(picFile(key), bytes);
|
|
543
|
+
data.pics[key] = { type, rev: `${hashOf(b64(bytes))}${bytes.length.toString(36)}`, at: nowS() };
|
|
544
|
+
};
|
|
545
|
+
const picDrop = (key) => { if (!data.pics[key]) return false; store.writePicture(picFile(key), null); delete data.pics[key]; return true; };
|
|
546
|
+
// Mine to each contact known to read pictures that does not have this one (or its removal) yet: one body each.
|
|
547
|
+
let picturing = false;
|
|
548
|
+
function picturesDue() {
|
|
549
|
+
if (picturing || !store.writePicture || live.seatGone !== null) return;
|
|
550
|
+
const rev = picRev('me') ?? '';
|
|
551
|
+
const due = carrier.contacts().contacts.filter((x) => !x.revoked && !hidden(x) && (x.seen_peer || data.pic_peer[x.did]) && (data.pic_sent[x.did] ?? '') !== rev);
|
|
552
|
+
if (!due.length) return;
|
|
553
|
+
picturing = true;
|
|
554
|
+
const bytes = rev ? store.readPicture(picFile('me')) : null;
|
|
555
|
+
const content = bytes ? { type: data.pics.me.type, data: b64(bytes) } : { remove: true };
|
|
556
|
+
void serial(async () => {
|
|
557
|
+
for (const x of due) {
|
|
558
|
+
try { const [r] = await carrier.sendAll(x.did, [content], { label: PICTURE_LABEL }); if (r.status !== 'refused') data.pic_sent[x.did] = rev; } catch (e) { if (/queued/.test(e.message)) data.pic_sent[x.did] = rev; }
|
|
559
|
+
}
|
|
560
|
+
saveData();
|
|
561
|
+
}).catch(() => {}).finally(() => { picturing = false; if ((picRev('me') ?? '') !== rev) picturesDue(); });
|
|
562
|
+
}
|
|
563
|
+
// A contact's picture (or its removal): checked, kept as t:<did>; it reads pictures, so mine goes too.
|
|
564
|
+
function takePicture(m) {
|
|
565
|
+
const d = String(m['from']), v = m['content'];
|
|
566
|
+
try {
|
|
567
|
+
if (v?.remove === true) picDrop(`t:${d}`);
|
|
568
|
+
else picSave(`t:${d}`, v?.type, pictureBytes(v?.type, v?.data));
|
|
569
|
+
data.pic_peer[d] = true; saveData();
|
|
570
|
+
defer(() => picturesDue());
|
|
571
|
+
} catch (e) { record({ kind: 'event', type: 'dropped', did: d, name: m['name'], code: 'picture', detail: e.message }); }
|
|
572
|
+
}
|
|
573
|
+
|
|
197
574
|
let timers = [];
|
|
198
575
|
async function start() {
|
|
199
576
|
void checkClock();
|
|
200
577
|
timers = [every(() => void checkClock(), 600_000), every(() => void drain().then(() => linkRound()), 60_000)];
|
|
201
|
-
|
|
578
|
+
// The enrolments from before this start (the pending file): their requests held, a failed identity sent again.
|
|
579
|
+
try { await look(); } catch {}
|
|
580
|
+
await carrier.start({ started: 'user' });
|
|
202
581
|
await drain();
|
|
203
582
|
void linkRound();
|
|
583
|
+
picturesDue();
|
|
584
|
+
void transfers?.engine.kick();
|
|
204
585
|
}
|
|
205
586
|
async function halt() {
|
|
206
587
|
for (const t of timers) clearInterval(t);
|
|
207
588
|
await linking.catch(() => {});
|
|
589
|
+
await transfers?.engine.close().catch(() => {});
|
|
590
|
+
line.close();
|
|
208
591
|
}
|
|
209
592
|
|
|
210
593
|
|
|
211
594
|
// ---- agents: the operator's workers (keeper `workers`), enrolled by a one-time code from this page
|
|
212
595
|
const K = hooks.keeper ?? null;
|
|
596
|
+
// The computer this profile is paired to, for the keeper (design/agent-wallet-page.md §4): { name() → its name,
|
|
597
|
+
// call(method, path, body?) → { status, body } } (its page over the control, scope all), or none.
|
|
598
|
+
const PC = hooks.computer ?? null;
|
|
599
|
+
const viaPc = async (method, path, body) => {
|
|
600
|
+
let r;
|
|
601
|
+
try { r = await PC.call(method, path, body); } catch (e) { return refuse(409, 'keeper_computer', `${PC.name()} isn't answering (${e?.message ?? 'no answer'}). Its keeper is set there.`); }
|
|
602
|
+
if (r.status !== 200) return refuse(r.status, r.body?.error?.check ?? 'keeper_computer', r.body?.error?.message ?? `${PC.name()} answered ${r.status}`);
|
|
603
|
+
return r.body;
|
|
604
|
+
};
|
|
213
605
|
const pend = (fn) => E.pending(enrolFile, nowS(), fn, carrier.platform);
|
|
214
606
|
const LIVE = new Set(['code', 'words', 'sending']);
|
|
607
|
+
// The pending file's enrolments as look() last read them (alive, not done): id → { temp, i, name, needs_send }. They outlive
|
|
608
|
+
// the page (a restart forgets `enrolling`): a request from their temporary DID is still answered, and an identity whose
|
|
609
|
+
// send failed (needs_send, enrol.mjs) still goes again, at agentRound.
|
|
610
|
+
let issuedLive = new Map();
|
|
611
|
+
const needsSend = () => [...issuedLive.values()].some((f) => f.needs_send);
|
|
215
612
|
function enrolHidden(x) {
|
|
216
613
|
for (const e of enrolling.values()) {
|
|
217
614
|
if (x.did !== undefined && x.did !== null && (x.did === e.temp || (LIVE.has(e.state) && carrier.answeredBy(e.id) === x.did))) return true;
|
|
218
615
|
if (x.name === `${e.name} (enrolling)` && LIVE.has(e.state)) return true;
|
|
219
616
|
}
|
|
617
|
+
// After a restart (0.1.16: the temporary identity showed in Chats with a chat and Pay): the pending file's enrolments.
|
|
618
|
+
for (const [id, f] of issuedLive) {
|
|
619
|
+
if (x.did !== undefined && x.did !== null && (x.did === f.temp || carrier.answeredBy(id) === x.did)) return true;
|
|
620
|
+
if (x.name === `${f.name ?? `worker ${f.i}`} (enrolling)`) return true;
|
|
621
|
+
}
|
|
220
622
|
return false;
|
|
221
623
|
}
|
|
222
624
|
// An enrolment request from the DID that answered one of this page's codes: kept for agentRound, not the devices'.
|
|
@@ -225,17 +627,32 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
225
627
|
for (const e of enrolling.values()) {
|
|
226
628
|
if (LIVE.has(e.state) && (e.temp === m['from'] || carrier.answeredBy(e.id) === m['from'])) { agentHeld.push(m); return true; }
|
|
227
629
|
}
|
|
630
|
+
for (const [id, f] of issuedLive) if (f.temp === m['from'] || carrier.answeredBy(id) === m['from']) { agentHeld.push(m); return true; }
|
|
228
631
|
return false;
|
|
229
632
|
}
|
|
230
|
-
const agentsBusy = () => agentHeld.length > 0 || [...enrolling.values()].some((e) => LIVE.has(e.state));
|
|
633
|
+
const agentsBusy = () => agentHeld.length > 0 || needsSend() || [...enrolling.values()].some((e) => LIVE.has(e.state));
|
|
231
634
|
const keeperOr = async () => (K ? await K.read() : null) ?? refuse(400, 'keeper', 'no keeper root here: your 25 words make it (sigelo-agent keeper --from-words on a computer; in the app, Create or Restore from seed)');
|
|
232
635
|
const seatHere = () => { const st = hooks.seat?.(); if (st && st.here === false) refuse(409, 'seat_elsewhere', `the seat is with ${st.holder}: agents are enrolled there (DEVICES.md)`); };
|
|
233
636
|
const pub = (e) => ({ id: e.id, state: e.state, code: e.state === 'code' ? e.short : null, exp: e.exp, relay: e.relay, words: e.words ?? null,
|
|
637
|
+
confirm_words: e.confirmWords === true, words_ok: e.wordsOk ?? null, verified: e.verified === true, needs_send: issuedLive.get(e.id)?.needs_send === true,
|
|
234
638
|
command: e.state === 'code' ? `${e.relay !== DEFAULT_RELAY ? `SIGELO_RELAY=${e.relay} ` : ''}sigelo-agent init --enrol ${e.short}` : null, ...(e.check !== undefined && { check: e.check, detail: e.detail ?? null }) });
|
|
235
639
|
// Who answered each code (its four words), codes dead unanswered (the index free again), enrolments done.
|
|
236
640
|
async function look() {
|
|
237
641
|
if (!enrolFile) return;
|
|
238
|
-
const t = nowS(), issued = pend((st) => Object.fromEntries(Object.entries(st.issued).map(([id, e]) => [id, { done: e.done ?? null
|
|
642
|
+
const t = nowS(), issued = pend((st) => Object.fromEntries(Object.entries(st.issued).map(([id, e]) => [id, { done: e.done ?? null, temp: e.temp ?? null, i: e.i, name: e.name ?? null, needs_send: e.needs_send !== undefined,
|
|
643
|
+
page: e.page ?? null, confirm_words: e.confirm_words === true, words_ok: e.words_ok ?? null, did: e.did, original: e.original, relay: e.relay, sent: e.sent_at !== undefined, held: e.held !== undefined,
|
|
644
|
+
told: e.temp && st.told?.[e.temp] ? { check: st.told[e.temp].check, detail: st.told[e.temp].detail ?? '' } : null }])));
|
|
645
|
+
issuedLive = new Map(Object.entries(issued).filter(([, f]) => !f.done));
|
|
646
|
+
// This page's enrolments come back from the pending file after a restart (0.1.17: an app killed in the background
|
|
647
|
+
// forgot them: the four words never showed and the request was never answered): the code, the words, the answer.
|
|
648
|
+
for (const [id, f] of issuedLive) {
|
|
649
|
+
if (enrolling.has(id) || !f.page) continue;
|
|
650
|
+
const by = f.temp ?? carrier.answeredBy(id);
|
|
651
|
+
enrolling.set(id, { id, worker: f.i, name: f.name, short: f.page.short, code: f.page.short, exp: f.page.short_exp, relay: f.relay, tier: f.page.tier ?? 'own',
|
|
652
|
+
state: f.sent || f.needs_send ? 'sending' : by ? 'words' : 'code', did: f.did, original: f.original, confirmWords: f.confirm_words, ...(f.words_ok !== null && { wordsOk: f.words_ok }),
|
|
653
|
+
...(by && { temp: by, words: carrier.contacts().contacts.find((x) => x.did === by)?.fingerprint ?? null }) });
|
|
654
|
+
changed();
|
|
655
|
+
}
|
|
239
656
|
for (const e of enrolling.values()) {
|
|
240
657
|
if (!LIVE.has(e.state)) continue;
|
|
241
658
|
const f = issued[e.id];
|
|
@@ -247,7 +664,9 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
247
664
|
e.temp = by; e.state = 'words';
|
|
248
665
|
e.words = carrier.contacts().contacts.find((x) => x.did === by)?.fingerprint ?? null;
|
|
249
666
|
changed();
|
|
250
|
-
} else if (t > e.exp + 30) {
|
|
667
|
+
} else if (t > e.exp + 30 && drainedOnline > (e.exp + 30) * 1000) {
|
|
668
|
+
// Run out, and read: only once a drain while online came after its end, so an answer the relay held while
|
|
669
|
+
// this page was away (in the background, reconnecting) is taken first (0.1.17: it was dropped as expired).
|
|
251
670
|
e.state = 'expired';
|
|
252
671
|
pend((st) => { delete st.issued[e.id]; });
|
|
253
672
|
try { await carrier.cancelInvite(e.code); } catch {}
|
|
@@ -260,20 +679,31 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
260
679
|
async function agentRound() {
|
|
261
680
|
await look();
|
|
262
681
|
const pass = agentHeld.splice(0);
|
|
263
|
-
if (!pass.length && ![...enrolling.values()].some((e) => e.state === 'words' || e.state === 'sending')) return;
|
|
682
|
+
if (!pass.length && !needsSend() && ![...issuedLive.values()].some((f) => f.held) && ![...enrolling.values()].some((e) => e.state === 'words' || e.state === 'sending')) return;
|
|
264
683
|
const k = await K?.read();
|
|
265
684
|
if (!k) return;
|
|
266
685
|
const root = await K.root(k);
|
|
267
686
|
// The carrier as enrolment sees it: its inbox is what the page kept apart.
|
|
268
687
|
const proxy = new Proxy(carrier, { get: (x, p) => (p === 'inbox' ? async () => ({ messages: pass.splice(0), events: [], dropped: {} }) : typeof x[p] === 'function' ? x[p].bind(x) : x[p]) });
|
|
688
|
+
// The optional switch: the key waits for "They match" (null: not yet, the request kept for the next round).
|
|
689
|
+
const confirm = async (o) => { if (!o.ask) return true; const e = enrolling.get(o.id); if (e && !e.words) e.words = o.words; return e?.wordsOk ?? issuedLive.get(o.id)?.words_ok ?? null; };
|
|
269
690
|
let res;
|
|
270
|
-
try { res = await E.complete({ carrier: proxy, file: enrolFile, keeper: root, wait: 0 }); } finally { root.K.fill(0); }
|
|
691
|
+
try { res = await E.complete({ carrier: proxy, file: enrolFile, keeper: root, wait: 0, confirm }); } finally { root.K.fill(0); }
|
|
692
|
+
// Held requests stay in the pending file (enrol.mjs "A request held"): the next round takes them again.
|
|
693
|
+
await look(); // needs_send as enrol.mjs left it
|
|
271
694
|
for (const d of res.delivered) { const e = enrolling.get(d.id); if (e) e.state = 'sending'; }
|
|
272
|
-
|
|
273
|
-
|
|
695
|
+
// What the machine is told (enrol.mjs toldFor: its words, no DID), shown here the same.
|
|
696
|
+
for (const x of [...res.refused.map((y) => ({ to: y.from, check: y.check, detail: E.toldFor(y.check, y.detail) })), ...res.told]) {
|
|
697
|
+
const e = [...enrolling.values()].find((y) => y.temp !== undefined && y.temp === x.to);
|
|
274
698
|
if (e) Object.assign(e, { check: x.check, detail: x.detail });
|
|
275
699
|
}
|
|
276
|
-
for (const p of res.placed) {
|
|
700
|
+
for (const p of res.placed) {
|
|
701
|
+
const e = enrolling.get(p.id);
|
|
702
|
+
if (e) Object.assign(e, { state: 'enrolled', at: nowS(), did: p.did, verified: p.verified === true });
|
|
703
|
+
// Worker i of these words, derived here: checked as "They match" checks a contact (no tap).
|
|
704
|
+
const c = p.verified ? carrier.contacts().contacts.find((x) => x.did === p.original && !x.revoked) : null;
|
|
705
|
+
if (c) { data.checked[c.did] = c.pair ?? ''; saveData(); }
|
|
706
|
+
}
|
|
277
707
|
changed();
|
|
278
708
|
}
|
|
279
709
|
const workerOf = (k, v) => {
|
|
@@ -282,17 +712,39 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
282
712
|
};
|
|
283
713
|
// The contact holding a worker's original DID, live, or null.
|
|
284
714
|
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"): an agent when the page knows it is one (my agent: ours by its operator
|
|
716
|
+
// attestation, on this machine, or a worker of my keeper root; a member a group roster names an agent), else a
|
|
717
|
+
// person; the human's choice (POST /api/kind, data.kind) wins.
|
|
718
|
+
let workerDids = new Set();
|
|
719
|
+
const rosterAgents = () => {
|
|
720
|
+
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
|
+
};
|
|
722
|
+
const kindOf = (x, mine, roles) => {
|
|
723
|
+
const set = data.kind[x.did];
|
|
724
|
+
if (set === 'agent' || set === 'person') return { kind: set, kind_set: true };
|
|
725
|
+
const agent = x.ours === true || mine !== null || x.chain.some((d) => workerDids.has(d) || roles.has(d));
|
|
726
|
+
return { kind: agent ? 'agent' : 'person', kind_set: false };
|
|
727
|
+
};
|
|
728
|
+
const orphan = (n) => {
|
|
729
|
+
const hit = [...issuedLive].find(([, f]) => f.i === n);
|
|
730
|
+
return hit ? { id: hit[0], state: hit[1].needs_send ? 'sending' : 'waiting', code: null, exp: null, relay: null, words: null, confirm_words: false, words_ok: null, verified: false, needs_send: hit[1].needs_send, command: null,
|
|
731
|
+
...(hit[1].told && { check: hit[1].told.check, detail: hit[1].told.detail }) } : null;
|
|
732
|
+
};
|
|
285
733
|
async function workers() {
|
|
286
734
|
const k = K ? await K.read() : null, st = hooks.seat?.() ?? null, seat = st ? (st.here ? 'here' : 'elsewhere') : null;
|
|
287
735
|
if (!k) return { keeper: false, seat, workers: [] };
|
|
288
736
|
await look();
|
|
289
737
|
const local = hooks.agents?.() ?? [], waiting = enrolFile ? pend((x) => Object.values(x.issued).filter((e) => !e.done).map((e) => e.i)) : [];
|
|
738
|
+
workerDids = new Set(Object.values(k.workers).filter((w) => w.revoked === undefined).map((w) => w.original));
|
|
290
739
|
const rows = Object.entries(k.workers).map(([i, w]) => {
|
|
291
740
|
const n = Number(i), c = contactOfWorker(w), here = local.find((a) => a.did === w.original), e = [...enrolling.values()].filter((x) => x.worker === n).at(-1);
|
|
292
741
|
const status = w.revoked !== undefined ? 'revoked' : c || here ? 'enrolled' : (e && LIVE.has(e.state)) || waiting.includes(n) ? 'pending' : 'unplaced';
|
|
293
|
-
return { worker: n, name: w.name, did: c?.current_did ?? w.did, original: w.original, rank: w.rank ?? null, placed: w.placed, at: w.at, status, revoked: w.revoked ?? null,
|
|
742
|
+
return { worker: n, name: w.name, did: c?.current_did ?? w.did, original: w.original, words: didWords(w.original), rank: w.rank ?? null, placed: w.placed, at: w.at, status, revoked: w.revoked ?? null,
|
|
294
743
|
seen: c ? seen(c.did) : null, tier: c?.tier ?? null, contact: c?.did ?? null, local: here?.name ?? null,
|
|
295
|
-
|
|
744
|
+
online: c?.online ?? null, last_seen: c?.last_seen ?? null,
|
|
745
|
+
attested_until: here?.mine?.exp ?? w.until ?? w.attestation?.body?.exp ?? null,
|
|
746
|
+
// Not in this page's memory (made before a restart): what the pending file says, sending again or waiting for the machine.
|
|
747
|
+
enrolling: e && e.state !== 'expired' ? pub(e) : status === 'pending' ? orphan(n) : null };
|
|
296
748
|
}).sort((a, b) => a.worker - b.worker);
|
|
297
749
|
return { keeper: true, seat, workers: rows };
|
|
298
750
|
}
|
|
@@ -300,7 +752,7 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
300
752
|
// ---- reads
|
|
301
753
|
const textOf = (v) => (typeof v === 'string' ? v : JSON.stringify(v));
|
|
302
754
|
function state(since) {
|
|
303
|
-
const t = nowS(), c = carrier.contacts(), local = hooks.agents?.() ?? [], clock = carrier.clockOffset();
|
|
755
|
+
const t = nowS(), c = carrier.contacts(), local = hooks.agents?.() ?? [], clock = carrier.clockOffset(), roles = rosterAgents();
|
|
304
756
|
const live_ = c.contacts.filter((x) => !x.revoked && !hidden(x)).map((x) => {
|
|
305
757
|
const pair = x.pair, agent = local.find((a) => a.did !== undefined && x.chain.includes(a.did));
|
|
306
758
|
const mine = agent?.mine ?? null;
|
|
@@ -313,37 +765,65 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
313
765
|
const last = msgs.at(-1), read = data.read[x.did] ?? 0;
|
|
314
766
|
const queued = msgs.filter((r) => r.kind === 'out' && r.status === 'queued');
|
|
315
767
|
return {
|
|
316
|
-
did: x.did, name: x.name, current_did: x.current_did, relay: x.relay, re_pair: x.re_pair, words: x.fingerprint, pair,
|
|
768
|
+
did: x.did, name: x.name, name_from: x.name_from ?? null, current_did: x.current_did, relay: x.relay, re_pair: x.re_pair, words: x.fingerprint, pair,
|
|
317
769
|
words_checked: pair !== null && data.checked[x.did] === pair, tags: data.tags[x.did] ?? [],
|
|
318
|
-
|
|
319
|
-
|
|
770
|
+
// Came by a public code (carrier.mjs via): mine ({public: id}, nobody compared) or theirs ({public: true, words}).
|
|
771
|
+
via: x.via ?? null,
|
|
772
|
+
local: agent?.name ?? null, mine, unread: msgs.filter((r) => r.kind === 'in' && r.n > read && (!r.call || r.call.state === 'missed')).length,
|
|
773
|
+
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
|
+
notify: notifyOf(x.did), seen_upto: x.seen_upto ?? null,
|
|
775
|
+
// 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,
|
|
777
|
+
picture: picRev(picOf(x.did) ?? ''), picture_local: data.pics[`l:${x.did}`] !== undefined,
|
|
320
778
|
waiting, not_collected: queued.length, queued: x.queued,
|
|
321
779
|
status: x.re_pair ? 'pair_again' : waiting ? 'waiting' : queued.length ? 'not_collected' : 'ok', ours: x.ours === true || mine !== null, tier,
|
|
322
780
|
link: x.link ? { id: x.link.id, purpose: x.link.purpose, linked_by: x.link.linked_by, expires: x.link.expires ?? null } : null,
|
|
781
|
+
// Presence (carrier.mjs): theirs as read now (online true, false, null: not known), and what they see of mine.
|
|
782
|
+
online: x.online ?? null, online_since: x.online_since ?? null, last_seen: x.last_seen ?? null, presence: x.presence ?? 'deny',
|
|
783
|
+
// Calls: may it ring here ("Can call me"), and whether that is my choice for it or the default.
|
|
784
|
+
can_call: canCall(x), can_call_set: typeof data.calls[x.did] === 'boolean',
|
|
785
|
+
...kindOf(x, mine, roles),
|
|
323
786
|
};
|
|
324
787
|
});
|
|
325
788
|
// Mine: ours by key, whatever the tier (an own agent set to friend is still mine), or tier own.
|
|
326
789
|
const isMine = (x) => x.ours || x.tier === 'own';
|
|
327
790
|
const mineGroup = live_.filter(isMine), rest = live_.filter((x) => !isMine(x));
|
|
328
791
|
const pendingInvites = c.invites.filter((p) => !hidden(p)).map((p) => {
|
|
792
|
+
if (p.renew) {
|
|
793
|
+
// A renewing code: the current one of its series, wherever it was made (the long code only for the first, made here).
|
|
794
|
+
const ours = invites.get(`r${p.renew}`), x = c.renewing?.find((y) => y.id === p.renew);
|
|
795
|
+
return { name: p.name, exp: p.exp, relay: p.relay, id: `r${p.renew}`, short: p.short ?? null, short_exp: p.short_exp ?? null, code: ours?.short === p.short ? ours.code : null, group: null,
|
|
796
|
+
renew: true, used: (x?.used ?? []).map((u) => ({ short: u.short, name: u.name, did: u.did, at: u.at })), renew_error: x?.error ?? null };
|
|
797
|
+
}
|
|
329
798
|
const ours = [...invites.values()].find((x) => x.name === p.name);
|
|
330
|
-
return { name: p.name, exp: p.exp, relay: p.relay, ...(ours && { id: ours.id, short: ours.short ?? null, short_exp: ours.short_exp ?? null, code: ours.code }) };
|
|
799
|
+
return { name: p.name, exp: p.exp, relay: p.relay, ...(ours && { id: ours.id, short: ours.short ?? null, short_exp: ours.short_exp ?? null, code: ours.code, group: ours.group ?? null }) };
|
|
331
800
|
});
|
|
332
801
|
const paired = [...invites.values()].filter((x) => x.paired).map((x) => ({ id: x.id, name: x.name, paired: x.paired }));
|
|
333
802
|
const failed = recs.filter((r) => r.kind === 'event' && r.type === 'pairing_failed' && r.at > t - DAY).slice(-5).map((r) => ({ name: r.name, did: r.did, code: r.code, detail: r.detail, at: r.at }));
|
|
334
803
|
const m = hooks.me();
|
|
335
804
|
return {
|
|
336
805
|
seq, now: t,
|
|
806
|
+
// Enrolments whose four words wait for the human (this page's): said on every tab, not only on Agents (0.1.17).
|
|
807
|
+
enrol_words: [...enrolling.values()].filter((e) => e.state === 'words' && e.confirmWords && e.wordsOk === undefined && e.words).map((e) => ({ id: e.id, name: e.name })),
|
|
337
808
|
me: {
|
|
338
809
|
did: m.did, relay: carrier.relay, online: live.online.has(carrier.relay), clock_offset: clock?.offset ?? null, clock_checked: clock?.checked ?? null,
|
|
339
810
|
retention_days: carrier.retentionDays, error: live.error, pow_done_ms: live.powDone,
|
|
340
811
|
// The seat (DEVICES.md): null without one; here false = another device logs in as you: the page shows a banner.
|
|
341
812
|
seat: hooks.seat?.() ?? null,
|
|
342
|
-
pow: live.pow && { bits: live.pow.bits, elapsed_s: Math.round((Date.now() - live.pow.since) / 1000), expected_s: Math.ceil(2 ** live.pow.bits /
|
|
813
|
+
pow: live.pow && { bits: live.pow.bits, elapsed_s: Math.round((Date.now() - live.pow.since) / 1000), expected_s: Math.ceil((2 ** live.pow.bits * POW_EVAL_MS * (live.pow.m * live.pow.t) / (POW_COST.m * POW_COST.t)) / 1000) },
|
|
814
|
+
pow_capped: live.powCapped, pow_confirm: live.powConfirm,
|
|
815
|
+
// Wallet (Settings → Wallet): the switch and the price choice, for every scope of a control.
|
|
816
|
+
wallet: (({ wallet, prices, currency }) => ({ on: wallet, prices, currency }))(walletSet()),
|
|
817
|
+
picture: picRev('me'),
|
|
343
818
|
},
|
|
344
819
|
groups: { mine: mineGroup, contacts: rest },
|
|
345
|
-
|
|
820
|
+
// Chat groups (GROUPS.md): the tab's badge and its notices; the list is GET /api/groups.
|
|
821
|
+
chats: chatsState(),
|
|
822
|
+
pending: { invites: pendingInvites, paired, answers: c.answers, failed, public: publicInvite(c), publics: c.publics ?? [] },
|
|
346
823
|
introductions: introductions(c.contacts),
|
|
824
|
+
transfers: transferCounts(),
|
|
825
|
+
// The live call (GET /api/calls has the rest), or null: the page's call screen and its poll.
|
|
826
|
+
call: (({ id, did, name, dir, state } = {}) => (id ? { id, did, name, dir, state } : null))(line.view() ?? undefined),
|
|
347
827
|
events: recs.filter((r) => r.kind === 'event' && r.n > since).slice(-50),
|
|
348
828
|
};
|
|
349
829
|
}
|
|
@@ -353,10 +833,128 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
353
833
|
if (carrier.platform.files.read(linksFile) === null) return [];
|
|
354
834
|
try {
|
|
355
835
|
return L.list({ carrier, file: linksFile }).received.filter((x) => !x.answer && cs.find((c) => c.did === x.from)?.tier !== 'quiet')
|
|
356
|
-
.map((x) => ({ id: x.id, from: x.from, name: x.name ?? x.from, purpose: x.purpose }));
|
|
836
|
+
.map((x) => ({ id: x.id, from: x.from, name: x.name ?? x.from, purpose: x.purpose, peer_name: x.peer_name ?? null }));
|
|
357
837
|
} catch { return []; }
|
|
358
838
|
}
|
|
359
839
|
|
|
840
|
+
// Files offered and waiting for a yes, and those moving: the page's badge (GET /api/transfers has the rest).
|
|
841
|
+
function transferCounts() {
|
|
842
|
+
if (!transfers) return null;
|
|
843
|
+
try {
|
|
844
|
+
const l = transfers.lib.list({ carrier, identity: hooks.transfers.identity });
|
|
845
|
+
return { asked: l.in.filter((r) => r.state === 'asked').length, active: [...l.in, ...l.out].filter((r) => ['accepted', 'offering', 'active'].includes(r.state)).length };
|
|
846
|
+
} catch { return null; }
|
|
847
|
+
}
|
|
848
|
+
// ---- groups (GROUPS.md): the inbox side by code at each drain; the lists and the verbs below
|
|
849
|
+
const GROUP_NOTICES = 20;
|
|
850
|
+
const gfile = () => groupsFile ?? refuse(404, 'route', 'no groups here');
|
|
851
|
+
// A notice for the operator, kept until dismissed (data.gnotices): a stranger added, the creator gone, refusals.
|
|
852
|
+
const gnote = (n) => { data.gnotices.push({ id: hexOf(4), at: nowS(), ...n }); if (data.gnotices.length > GROUP_NOTICES) data.gnotices.splice(0, data.gnotices.length - GROUP_NOTICES); };
|
|
853
|
+
// The carrier's group messages checked and filed (handle), copies carried on and sent; every item is the
|
|
854
|
+
// page's to show (taken: no inbox beside a page). Invitations wait as status pending in the list.
|
|
855
|
+
async function groupRound() {
|
|
856
|
+
if (!G || !groupsFile) return;
|
|
857
|
+
try {
|
|
858
|
+
const r = await G.handle({ carrier, file: groupsFile });
|
|
859
|
+
let noted = false;
|
|
860
|
+
for (const n of r.notices) if (n.why !== 'invited') { gnote(n); noted = true; }
|
|
861
|
+
const by = new Map();
|
|
862
|
+
for (const x of r.refused) by.set(x.check, (by.get(x.check) ?? 0) + 1);
|
|
863
|
+
for (const [check, n] of by) { gnote({ type: 'group', why: 'refused', check, count: n }); noted = true; }
|
|
864
|
+
if (noted) saveData();
|
|
865
|
+
if (noted || r.filed || r.notices.length || r.joined.length || r.removed.length) changed();
|
|
866
|
+
} catch (err) { live.error = `groups: ${err.message}`; }
|
|
867
|
+
}
|
|
868
|
+
// Unread in a group: the items after the newest shown (data.gread), none of mine.
|
|
869
|
+
const unreadIn = (gid, items) => {
|
|
870
|
+
const m = data.gread[gid];
|
|
871
|
+
if (!m) return items.filter((i) => !i.mine).length;
|
|
872
|
+
const at = items.findIndex((i) => i.mid === m.mid);
|
|
873
|
+
return (at >= 0 ? items.slice(at + 1) : items.filter((i) => (i.received ?? 0) > m.at)).filter((i) => !i.mine).length;
|
|
874
|
+
};
|
|
875
|
+
const brakeQuiet = (g) => g.brake !== 'off' && g.run >= g.brake;
|
|
876
|
+
function groupsList() {
|
|
877
|
+
if (!G || !groupsFile) return [];
|
|
878
|
+
const gs = G.list({ carrier, file: groupsFile });
|
|
879
|
+
return gs.map((g) => {
|
|
880
|
+
const items = ['member', 'frozen'].includes(g.status) ? G.history({ carrier, file: groupsFile, group: g.gid }) : [];
|
|
881
|
+
const last = items.at(-1);
|
|
882
|
+
return { ...g, unread: unreadIn(g.gid, items), quiet: brakeQuiet(g), notify: notifyOf(g.gid), picture: picRev(`l:${g.gid}`),
|
|
883
|
+
last: last ? { name: last.mine ? null : last.name, text: textOf(last.content).slice(0, 200), at: last.received ?? last.iat, mine: last.mine === true } : null };
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
function groupTier() {
|
|
887
|
+
const told = carrier.groupTier ?? null, { lim, tier } = G.limitsFor(carrier);
|
|
888
|
+
return { tier, groups: lim.groups, members: lim.members, told: told !== null };
|
|
889
|
+
}
|
|
890
|
+
// /api/state's chats: the badge (unread in all), invitations waiting, notices. Never fails the state.
|
|
891
|
+
function chatsState() {
|
|
892
|
+
if (!G || !groupsFile || carrier.platform.files.read(groupsFile) === null) return { unread: 0, invited: 0, notices: data.gnotices.length, rev: `0.${data.gnotices.length}` };
|
|
893
|
+
try {
|
|
894
|
+
const gs = groupsList();
|
|
895
|
+
// rev: changes with any group's roster, status, run or newest item (the page fetches a chat again on it).
|
|
896
|
+
const rev = gs.map((g) => `${g.gid.slice(0, 8)}.${g.ver}.${g.status}.${g.run}.${g.last?.at ?? 0}.${g.unread}`).join(' ');
|
|
897
|
+
return { unread: gs.reduce((a, g) => a + g.unread, 0), invited: gs.filter((g) => g.status === 'pending').length, notices: data.gnotices.length, rev: `${hashOf(rev)}.${data.gnotices.length}` };
|
|
898
|
+
} catch { return { unread: 0, invited: 0, notices: data.gnotices.length, rev: '' }; }
|
|
899
|
+
}
|
|
900
|
+
// group.mjs refusals by check: unknown → 404, usage → 400, any other (group_*, not_contact, name) → 409.
|
|
901
|
+
async function groupCall(fn) {
|
|
902
|
+
gfile();
|
|
903
|
+
try { return await fn(); } catch (e) {
|
|
904
|
+
if (e.check !== undefined && e.status === undefined) e.status = ['group_unknown', 'not_contact'].includes(e.check) ? 404 : ['group_message', 'group_text', 'group_members'].includes(e.check) ? 400 : 409;
|
|
905
|
+
throw e;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
const gid = (b) => (typeof b['group'] === 'string' && b['group'] !== '' ? b['group'] : refuse(400, 'body', 'group: its gid'));
|
|
909
|
+
const isGroup = (x) => { try { return typeof x === 'string' && /^[0-9a-f]{32}$/.test(x) && Boolean(G && groupsFile && carrier.platform.files.read(groupsFile) !== null && G.list({ carrier, file: groupsFile }).some((g) => g.gid === x)); } catch { return false; } };
|
|
910
|
+
const dids = (v, what, need = true) => {
|
|
911
|
+
if (v === undefined && !need) return [];
|
|
912
|
+
if (!Array.isArray(v) || (need && v.length === 0) || v.length > 64 || v.some((x) => typeof x !== 'string' || x === '')) refuse(400, 'body', `${what}: a list of contact DIDs`);
|
|
913
|
+
return v;
|
|
914
|
+
};
|
|
915
|
+
// A write's answer: the group as the list shows it, and how its copies went.
|
|
916
|
+
const gout = (r) => ({ ...(r.group && { group: r.group }), copies: r.copies ?? [], ...(r.offline !== undefined && { offline: r.offline }) });
|
|
917
|
+
const groupRoutes = {
|
|
918
|
+
'GET /api/groups': () => groupCall(() => ({ tier: groupTier(), groups: groupsList(), notices: data.gnotices.slice() })),
|
|
919
|
+
'GET /api/groups/history': (_, q) => groupCall(() => {
|
|
920
|
+
const g = q.get('group') ?? refuse(400, 'body', 'group: its gid'), one = groupsList().find((x) => x.gid === g) ?? refuse(404, 'group_unknown', `no group ${g} here`);
|
|
921
|
+
const items = G.history({ carrier, file: groupsFile, group: g }), last = items.at(-1);
|
|
922
|
+
// Read: the page has shown them.
|
|
923
|
+
if (last && data.gread[g]?.mid !== last.mid) { data.gread[g] = { mid: last.mid, at: last.received ?? last.iat }; saveData(); }
|
|
924
|
+
return { group: { ...one, unread: 0 }, messages: items.slice(-200).map((i) => ({ mid: i.mid, re: i.re ?? null, from: i.from, name: i.name, role: i.role, tier: i.tier ?? null, mine: i.mine === true,
|
|
925
|
+
operator: i.operator === true, note: i.note ?? null, text: textOf(i.content), mentions: i.mentions ?? [], mentioned: i.mentioned === true, via: i.via ?? null, photo: i.photo ?? null, ...(i.voice && { voice: i.voice }), at: i.received ?? i.iat })) };
|
|
926
|
+
}),
|
|
927
|
+
'POST /api/groups/create': (b) => serial(() => groupCall(async () => {
|
|
928
|
+
const brake = b['brake'];
|
|
929
|
+
return gout(await G.create({ carrier, file: groupsFile, name: b['name'], members: dids(b['members'], 'members'), humans: dids(b['humans'], 'humans', false), ...(brake !== undefined && brake !== null && { brake }),
|
|
930
|
+
...(carrier.selfName() !== null && { selfName: carrier.selfName() }),
|
|
931
|
+
...(typeof b['role'] === 'string' && { role: b['role'] }) }));
|
|
932
|
+
})),
|
|
933
|
+
'POST /api/groups/add': (b) => serial(() => groupCall(async () => gout(await G.add({ carrier, file: groupsFile, group: gid(b), members: dids(b['members'], 'members'), humans: dids(b['humans'], 'humans', false) })))),
|
|
934
|
+
'POST /api/groups/remove': (b) => serial(() => groupCall(async () => gout(await G.remove({ carrier, file: groupsFile, group: gid(b), members: dids(b['members'], 'members') })))),
|
|
935
|
+
'POST /api/groups/rename': (b) => serial(() => groupCall(async () => gout(await G.rename({ carrier, file: groupsFile, group: gid(b), name: b['name'] })))),
|
|
936
|
+
'POST /api/groups/brake': (b) => serial(() => groupCall(async () => gout(await G.setBrake({ carrier, file: groupsFile, group: gid(b), brake: b['brake'] })))),
|
|
937
|
+
'POST /api/groups/role': (b) => serial(() => groupCall(async () => gout(await G.setRole({ carrier, file: groupsFile, group: gid(b), member: b['member'], role: b['role'] })))),
|
|
938
|
+
'POST /api/groups/share': (b) => serial(() => groupCall(async () => gout(await G.share({ carrier, file: groupsFile, group: gid(b), member: b['member'] })))),
|
|
939
|
+
'POST /api/groups/leave': (b) => serial(() => groupCall(async () => { const r = await G.leave({ carrier, file: groupsFile, group: gid(b) }); changed(); return { ...gout(r), told: r.told }; })),
|
|
940
|
+
'POST /api/groups/join': (b) => serial(() => groupCall(async () => { const r = G.join({ carrier, file: groupsFile, group: gid(b) }); changed(); return gout(r); })),
|
|
941
|
+
'POST /api/groups/send': (b) => serial(() => groupCall(async () => {
|
|
942
|
+
const text = b['text'], re = b['re'], mentions = b['mentions'];
|
|
943
|
+
if (typeof text !== 'string' || text.trim() === '') refuse(400, 'body', 'text: the message');
|
|
944
|
+
if (mentions !== undefined && (!Array.isArray(mentions) || mentions.some((x) => typeof x !== 'string'))) refuse(400, 'body', 'mentions: member DIDs or names');
|
|
945
|
+
const r = await G.send({ carrier, file: groupsFile, group: gid(b), text, ...(typeof re === 'string' && re !== '' && { re }), ...(mentions && { mentions }) });
|
|
946
|
+
changed();
|
|
947
|
+
return { gid: r.gid, mid: r.mid, copies: r.copies, via_creator: r.via_creator, unreached: r.unreached, ...(r.offline !== undefined && { offline: r.offline }) };
|
|
948
|
+
})),
|
|
949
|
+
'POST /api/groups/dismiss': (b) => serial(async () => {
|
|
950
|
+
const id = b['id'], before = data.gnotices.length;
|
|
951
|
+
data.gnotices = id === 'all' ? [] : data.gnotices.filter((n) => n.id !== id);
|
|
952
|
+
if (data.gnotices.length === before && id !== 'all') refuse(404, 'notice', 'no such notice');
|
|
953
|
+
saveData(); changed();
|
|
954
|
+
return { dismissed: before - data.gnotices.length };
|
|
955
|
+
}),
|
|
956
|
+
};
|
|
957
|
+
|
|
360
958
|
// ---- writes
|
|
361
959
|
const contactOf = (d) => {
|
|
362
960
|
if (typeof d !== 'string') refuse(400, 'body', 'contact: a DID');
|
|
@@ -375,30 +973,190 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
375
973
|
}
|
|
376
974
|
async function forget(c) {
|
|
377
975
|
const r = await carrier.forget(c.did);
|
|
378
|
-
delete data.tags[c.did]; delete data.checked[c.did];
|
|
976
|
+
delete data.tags[c.did]; delete data.checked[c.did]; delete data.kind[c.did];
|
|
977
|
+
if (store.writePicture) { picDrop(`l:${c.did}`); picDrop(`t:${c.did}`); }
|
|
978
|
+
delete data.pic_sent[c.did]; delete data.pic_peer[c.did]; saveData();
|
|
379
979
|
return { forgotten: c.did, offline: r.offline ?? null };
|
|
380
980
|
}
|
|
981
|
+
// Who signed a statement, as this page knows them: me, a contact (its chain holds the signing key), or nobody known.
|
|
982
|
+
function signerOf(v) {
|
|
983
|
+
const m = hooks.me();
|
|
984
|
+
if (v.original === m.original && m.chain.includes(v.did)) return { kind: 'me', did: m.original, name: null, words_checked: true };
|
|
985
|
+
const c = carrier.contacts().contacts.find((x) => !x.revoked && !hidden(x) && x.did === v.original && x.chain.includes(v.did));
|
|
986
|
+
return c ? { kind: 'contact', did: c.did, name: c.name, words_checked: c.pair !== null && data.checked[c.did] === c.pair } : { kind: 'unknown', did: v.original, name: null, words_checked: false };
|
|
987
|
+
}
|
|
988
|
+
const checked = (v) => (v.valid ? { ...v, words: didWords(v.original), by: signerOf(v) } : v);
|
|
989
|
+
// A statement in a chat (the bubble's "Signed by … · check"): checked once per message, kept for the page's life.
|
|
990
|
+
const statements = new Map();
|
|
991
|
+
function statementOf(r) {
|
|
992
|
+
let v = statements.get(r.n);
|
|
993
|
+
if (!v) { v = checkStatement(textOf(r.text), nowS()); statements.set(r.n, v); }
|
|
994
|
+
const w = checked(v);
|
|
995
|
+
return w.valid ? { valid: true, by: w.by, words: w.words, text: w.text, iat: w.iat } : { valid: false, check: w.check };
|
|
996
|
+
}
|
|
997
|
+
// POST /api/invite {public: true, months?, cap?, open?, name?}: a public code (the header's), Pro only (public_pro → 402).
|
|
998
|
+
async function publicRoute(b) {
|
|
999
|
+
const months = b['months'] ?? 6, cap = b['cap'] ?? 50;
|
|
1000
|
+
if (![1, 6, 12].includes(months)) refuse(400, 'body', 'months: 1, 6 or 12');
|
|
1001
|
+
if (!Number.isSafeInteger(cap) || cap < 1 || cap > 500) refuse(400, 'body', 'cap: new chats a day, 1 to 500');
|
|
1002
|
+
if (b['open'] !== undefined && typeof b['open'] !== 'boolean') refuse(400, 'body', 'open: true (let anyone in) or false (approve each, the default)');
|
|
1003
|
+
if (b['long'] !== undefined || b['group'] !== undefined || b['renew'] !== undefined || b['ttl'] !== undefined) refuse(400, 'body', 'public: with months, cap, open and name only');
|
|
1004
|
+
const name = b['name'] === undefined || b['name'] === '' ? undefined : cleanName(b['name'], 'name'), at = newCodes();
|
|
1005
|
+
const r = await carrier.invitePublic({ ...(name !== undefined && { name }), ttl: months === 12 ? 366 * DAY : months * 30 * DAY, cap, open: b['open'] === true, ...(at !== carrier.relay && { relay: at }), started: startedBy(b) })
|
|
1006
|
+
.catch((e) => { if (e.check === 'public_pro') e.status = 402; return Promise.reject(e); });
|
|
1007
|
+
changed();
|
|
1008
|
+
return { ...r, public: true };
|
|
1009
|
+
}
|
|
1010
|
+
// GET /api/search (UI-API.md "Search"): the contacts' histories (texts and signed messages; photos, voice and files are
|
|
1011
|
+
// not text) and the groups' (G.history, as GET /api/groups/history reads it), newest first. A read of what is here only:
|
|
1012
|
+
// no carrier call, no read mark, no receipt.
|
|
1013
|
+
const searchText = (r) => (r.label === STATEMENT_LABEL ? textOf(r.text).replace(/(?:^|\n)sigelo-statement\/0\s[\s\S]*$/, '').replace(SIGNED_LINE, '') : textOf(r.text));
|
|
1014
|
+
function search(q) {
|
|
1015
|
+
const want = foldMap(String(q.get('q') ?? '').trim()).f;
|
|
1016
|
+
if ([...want].length < 2) refuse(400, 'query', 'q: at least 2 characters');
|
|
1017
|
+
const lim = q.get('limit') === null ? 50 : Number(q.get('limit'));
|
|
1018
|
+
if (!Number.isSafeInteger(lim) || lim < 1 || lim > 200) refuse(400, 'body', 'limit: 1 to 200');
|
|
1019
|
+
const one = q.get('contact'), grp = q.get('group'), hits = [];
|
|
1020
|
+
if (one !== null && grp !== null) refuse(400, 'body', 'contact or group, not both');
|
|
1021
|
+
const hit = (base, t) => { const m = matchIn(t, want); if (m) hits.push({ ...base, text: t.slice(0, 1000), ...m }); };
|
|
1022
|
+
if (grp === null) {
|
|
1023
|
+
const by = new Map((one !== null ? [contactOf(one)] : carrier.contacts().contacts.filter((x) => !x.revoked && !hidden(x))).map((c) => [c.did, c]));
|
|
1024
|
+
for (const r of recs) {
|
|
1025
|
+
if ((r.kind !== 'in' && r.kind !== 'out') || !by.has(r.did) || r.photo || r.voice || r.file || [PHOTO_LABEL, VOICE_LABEL, FILE_LABEL].includes(r.label)) continue;
|
|
1026
|
+
hit({ chat: r.did, kind: 'contact', name: by.get(r.did).name, n: r.n, dir: r.kind, at: r.at }, searchText(r));
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
if (one === null) {
|
|
1030
|
+
const gs = G && groupsFile && carrier.platform.files.read(groupsFile) !== null ? G.list({ carrier, file: groupsFile }).filter((g) => grp === null || g.gid === grp) : [];
|
|
1031
|
+
if (grp !== null && !gs.length) refuse(404, 'group_unknown', `no group ${grp} here`);
|
|
1032
|
+
for (const g of gs) {
|
|
1033
|
+
let items = [];
|
|
1034
|
+
try { items = G.history({ carrier, file: groupsFile, group: g.gid }); } catch {}
|
|
1035
|
+
for (const i of items) if (!i.photo && !i.voice) hit({ chat: g.gid, kind: 'group', name: g.name, n: i.mid, dir: i.mine ? 'out' : 'in', at: i.received ?? i.iat }, textOf(i.content));
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
return { hits: hits.reverse().sort((a, b) => b.at - a.at).slice(0, lim) };
|
|
1039
|
+
}
|
|
381
1040
|
const routes = {
|
|
382
1041
|
'GET /api/state': async (_, q) => { if (draining) await draining; return state(Number(q.get('since') ?? 0) || 0); },
|
|
383
1042
|
'GET /api/me': () => {
|
|
384
1043
|
const m = hooks.me(), i = hooks.meInfo();
|
|
385
|
-
return { did: m.did, original: m.original, chain: m.chain, identity_file: i.identity_file, recovery: i.recovery, key: i.key, relay: carrier.relay, retention_days: carrier.retentionDays, erase: i.erase,
|
|
1044
|
+
return { did: m.did, original: m.original, words: didWords(m.original), chain: m.chain, identity_file: i.identity_file, recovery: i.recovery, key: i.key, relay: carrier.relay, retention_days: carrier.retentionDays, erase: i.erase,
|
|
386
1045
|
...(i.restored && { restored: i.restored }) };
|
|
387
1046
|
},
|
|
1047
|
+
// Pictures (the header's): of=me (mine), a contact's DID or a group's gid (the one shown: a local one, else theirs).
|
|
1048
|
+
'GET /api/picture': (_, q) => {
|
|
1049
|
+
const of = q.get('of') ?? '';
|
|
1050
|
+
if (of !== 'me' && !isGroup(of)) contactOf(of);
|
|
1051
|
+
const key = picOf(of), bytes = key && data.pics[key] ? store.readPicture?.(picFile(key)) ?? null : null;
|
|
1052
|
+
if (!bytes) refuse(404, 'picture_none', 'no picture: the initial or the mark shows');
|
|
1053
|
+
return { of, type: data.pics[key].type, data: b64(bytes), rev: data.pics[key].rev, local: key.startsWith('l:') };
|
|
1054
|
+
},
|
|
1055
|
+
'POST /api/picture': (b) => serial(async () => {
|
|
1056
|
+
if (!store.writePicture) refuse(404, 'route', 'no pictures here');
|
|
1057
|
+
const of = b['of'];
|
|
1058
|
+
if (typeof of !== 'string' || of === '') refuse(400, 'body', 'of: me, a contact\'s DID or a group\'s gid');
|
|
1059
|
+
const id = of === 'me' ? 'me' : isGroup(of) ? of : contactOf(of).did, key = id === 'me' ? 'me' : `l:${id}`;
|
|
1060
|
+
if (b['remove'] === true) picDrop(key);
|
|
1061
|
+
else picSave(key, b['type'], pictureBytes(b['type'], b['data']));
|
|
1062
|
+
saveData();
|
|
1063
|
+
if (id === 'me') picturesDue();
|
|
1064
|
+
changed();
|
|
1065
|
+
const now_ = picOf(id);
|
|
1066
|
+
return { of: id, picture: now_ ? picRev(now_) : null, local: now_?.startsWith('l:') ?? false };
|
|
1067
|
+
}),
|
|
1068
|
+
// Signed statements (the header's): sign a text with this identity's key; check one, offline.
|
|
1069
|
+
'POST /api/statement/sign': (b) => serial(async () => {
|
|
1070
|
+
const statement = signStatement(carrier.identity(), b['text'], nowS());
|
|
1071
|
+
return { statement, ...checked(checkStatement(statement, nowS())) };
|
|
1072
|
+
}),
|
|
1073
|
+
'POST /api/statement/check': async (b) => {
|
|
1074
|
+
if (typeof b['statement'] !== 'string' || b['statement'].length > 4 * TEXT_MAX) refuse(400, 'body', 'statement: the signed text, as it was shared');
|
|
1075
|
+
return checked(checkStatement(b['statement'], nowS()));
|
|
1076
|
+
},
|
|
1077
|
+
// Proof of age (Me → Proof of age): what this identity's own bundle shows of its age, checked (SPEC §9): the day its
|
|
1078
|
+
// genesis names (its own word) and each attestation a world signed, with when.
|
|
1079
|
+
'GET /api/attestations': () => {
|
|
1080
|
+
const bundle = carrier.identity().bundle, r = verify(bundle, nowS());
|
|
1081
|
+
const list = Object.entries(r.attestations ?? {}).flatMap(([iss, bodies]) => bodies.map((x) => ({ iss, ctx: x.ctx, iat: x.iat, exp: x.exp, admission: x.admission, claims: x.claims ?? {} })));
|
|
1082
|
+
return { created: bundle.genesis.created ?? null, attestations: list.sort((a, c) => a.iat - c.iat), rejected: r.rejected?.attestations ?? 0 };
|
|
1083
|
+
},
|
|
388
1084
|
'POST /api/invite': (b) => serial(async () => {
|
|
389
|
-
|
|
390
|
-
const
|
|
391
|
-
const
|
|
392
|
-
const
|
|
1085
|
+
if (b['public'] === true) return publicRoute(b);
|
|
1086
|
+
const pub = false, ttl = b['ttl'];
|
|
1087
|
+
const name = b['name'] === undefined || b['name'] === '' ? `${pub ? 'public' : 'contact'}-${hexOf(2)}` : cleanName(b['name'], 'name');
|
|
1088
|
+
const at = newCodes(), group = b['group'];
|
|
1089
|
+
// A long code's life (the public invite): an hour to 7 days; the short code lives 10 minutes whatever.
|
|
1090
|
+
if (ttl !== undefined && (b['long'] !== true || !Number.isSafeInteger(ttl) || ttl < 3600 || ttl > 7 * DAY)) refuse(400, 'body', 'ttl: with long, 3600 to 604800 seconds (an hour to 7 days)');
|
|
1091
|
+
if (b['public'] !== undefined && b['public'] !== false) refuse(400, 'body', 'public: true or false');
|
|
1092
|
+
// A person code that renews itself: short, for one person at a time (no long, public or group code).
|
|
1093
|
+
const renew = b['renew'] === true;
|
|
1094
|
+
if (b['renew'] !== undefined && (typeof b['renew'] !== 'boolean' || (renew && (b['long'] === true || pub || group !== undefined)))) refuse(400, 'body', 'renew: true, a short person code (not long, public or a group code)');
|
|
1095
|
+
// A group code (Add people): whoever pairs through it is added to that group of mine, as a person.
|
|
1096
|
+
if (group !== undefined) {
|
|
1097
|
+
const g = typeof group === 'string' && G && groupsFile ? G.list({ carrier, file: groupsFile }).find((x) => x.gid === group) : null;
|
|
1098
|
+
if (!g) refuse(404, 'group_unknown', `no group ${String(group)} here`);
|
|
1099
|
+
if (!g.mine || g.status !== 'member') refuse(409, 'group_creator', `only ${g.creator_name ?? 'its creator'} adds people to ${g.name}`);
|
|
1100
|
+
}
|
|
1101
|
+
// Unnamed: the made-up name gives way to the one the contact tells once paired (carrier.mjs "Names").
|
|
1102
|
+
const r = await carrier.invite({ name, named: !(b['name'] === undefined || b['name'] === ''), short: b['long'] !== true, ...(ttl !== undefined && { ttl }), ...(at !== carrier.relay && { relay: at }), ...(renew && { renew: true }), started: startedBy(b) });
|
|
1103
|
+
const inv = { id: r.renew ? `r${r.renew}` : hexOf(6), name, code: r.code, exp: r.exp, ...(r.short !== undefined && { short: r.short, short_exp: r.short_exp }), ...(group !== undefined && { group }), ...(pub && { public: true }), ...(r.renew && { renew: true }) };
|
|
393
1104
|
invites.set(inv.id, inv);
|
|
394
1105
|
changed();
|
|
395
1106
|
return { ...inv, relay: r.relay };
|
|
396
1107
|
}),
|
|
397
1108
|
'POST /api/invite/cancel': (b) => serial(async () => {
|
|
398
|
-
|
|
399
|
-
|
|
1109
|
+
// By its short code (a code this page did not make: the CLI's, a renewal), at the carrier and the relay.
|
|
1110
|
+
if (b['id'] === undefined && typeof b['code'] === 'string' && b['code'].trim() !== '') {
|
|
1111
|
+
const r = await carrier.cancelInvite(b['code'].trim()).catch((e) => (e.check === 'challenge_unknown' ? refuse(404, 'invite', 'no such invite') : Promise.reject(e)));
|
|
1112
|
+
for (const x of [...invites.values()]) if (x.short === r.short || (r.name !== null && x.name === r.name)) invites.delete(x.id);
|
|
1113
|
+
changed();
|
|
1114
|
+
return { cancelled: true, ...(r.unparked !== undefined && { unparked: r.unparked }), ...(r.detail && { detail: r.detail }) };
|
|
1115
|
+
}
|
|
1116
|
+
const id = String(b['id']);
|
|
1117
|
+
// A renewing code: its series' current code, wherever it was made; cancelling it ends the series.
|
|
1118
|
+
if (id.startsWith('r')) {
|
|
1119
|
+
const cur = carrier.contacts().invites.find((x) => `r${x.renew}` === id);
|
|
1120
|
+
invites.delete(id);
|
|
1121
|
+
if (!cur) refuse(404, 'invite', 'no such invite');
|
|
1122
|
+
const r = cur.short ? await carrier.cancelInvite(cur.short) : { unparked: undefined };
|
|
1123
|
+
changed();
|
|
1124
|
+
return { cancelled: true, ...(r.unparked !== undefined && { unparked: r.unparked }), ...(r.detail && { detail: r.detail }) };
|
|
1125
|
+
}
|
|
1126
|
+
// A public code of mine (its id): Revoke for all.
|
|
1127
|
+
if (carrier.publics().some((x) => x.id === id)) {
|
|
1128
|
+
const r = await carrier.cancelInvite(id);
|
|
1129
|
+
changed();
|
|
1130
|
+
return { cancelled: true, public: true, unparked: r.unparked, ...(r.detail && { detail: r.detail }) };
|
|
1131
|
+
}
|
|
1132
|
+
const inv = invites.get(id) ?? refuse(404, 'invite', 'no such invite');
|
|
1133
|
+
let r = {};
|
|
1134
|
+
try { r = await carrier.cancelInvite(inv.code); } catch (e) { if (!inv.public) throw e; }
|
|
400
1135
|
invites.delete(inv.id);
|
|
401
|
-
|
|
1136
|
+
changed();
|
|
1137
|
+
return { cancelled: true, ...(r.unparked !== undefined && { unparked: r.unparked }), ...(r.detail && { detail: r.detail }) };
|
|
1138
|
+
}),
|
|
1139
|
+
// A public code's requests and settings (UI-API.md "Public invite").
|
|
1140
|
+
'POST /api/public/approve': (b) => serial(async () => {
|
|
1141
|
+
if (typeof b['id'] !== 'string') refuse(400, 'body', 'id: a request\'s id (pending.public.requests[].id)');
|
|
1142
|
+
const r = await carrier.approvePublic(b['id'], { started: startedBy(b) }).catch((e) => (e.check === 'challenge_unknown' ? refuse(404, 'request', e.message) : Promise.reject(e)));
|
|
1143
|
+
changed();
|
|
1144
|
+
return r;
|
|
1145
|
+
}),
|
|
1146
|
+
'POST /api/public/refuse': (b) => serial(async () => {
|
|
1147
|
+
if (typeof b['id'] !== 'string') refuse(400, 'body', 'id: a request\'s id');
|
|
1148
|
+
try { const r = carrier.refusePublic(b['id']); changed(); return r; } catch (e) { if (e.check === 'challenge_unknown') refuse(404, 'request', e.message); throw e; }
|
|
1149
|
+
}),
|
|
1150
|
+
'POST /api/public/set': (b) => serial(async () => {
|
|
1151
|
+
const id = b['id'] ?? carrier.publics()[0]?.id;
|
|
1152
|
+
if (typeof id !== 'string') refuse(404, 'public', 'no public code here');
|
|
1153
|
+
if (b['paused'] !== undefined && typeof b['paused'] !== 'boolean') refuse(400, 'body', 'paused: true or false');
|
|
1154
|
+
if (b['cap'] !== undefined && (!Number.isSafeInteger(b['cap']) || b['cap'] < 1 || b['cap'] > 500)) refuse(400, 'body', 'cap: new chats a day, 1 to 500');
|
|
1155
|
+
if (b['paused'] === undefined && b['cap'] === undefined) refuse(400, 'body', 'paused and/or cap');
|
|
1156
|
+
const r = await carrier.setPublic(id, { ...(b['paused'] !== undefined && { paused: b['paused'] }), ...(b['cap'] !== undefined && { cap: b['cap'] }) }, { started: startedBy(b) })
|
|
1157
|
+
.catch((e) => (e.check === 'challenge_unknown' ? refuse(404, 'public', e.message) : Promise.reject(e)));
|
|
1158
|
+
changed();
|
|
1159
|
+
return r;
|
|
402
1160
|
}),
|
|
403
1161
|
'POST /api/accept': (b) => serial(async () => {
|
|
404
1162
|
if (typeof b['code'] !== 'string' || b['code'].trim() === '') refuse(400, 'body', 'code: the short code (K7F3-Q9ZP) or the long one (sgl1…)');
|
|
@@ -407,7 +1165,10 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
407
1165
|
// friend or quiet, the human's choice; own is detected, never asked (store.mjs tiers).
|
|
408
1166
|
const tier = b['tier'];
|
|
409
1167
|
if (tier !== undefined && tier !== 'friend' && tier !== 'quiet') refuse(400, 'body', 'tier: friend or quiet');
|
|
410
|
-
|
|
1168
|
+
// words: a public code's four words, as its page printed them (checked on the reply).
|
|
1169
|
+
if (b['words'] !== undefined && (typeof b['words'] !== 'string' || b['words'].trim() === '')) refuse(400, 'body', 'words: the four words beside a public code');
|
|
1170
|
+
const words = typeof b['words'] === 'string' ? b['words'] : undefined;
|
|
1171
|
+
const r = await carrier.accept(code, { ...(name !== undefined && { name }), wait: 10, ...(tier !== undefined && { tier }), ...(words !== undefined && { words }), started: startedBy(b) });
|
|
411
1172
|
const now = r.contact ? carrier.contacts().contacts.find((x) => x.did === r.contact.did) : undefined;
|
|
412
1173
|
return r.contact ? { status: r.status, contact: { ...r.contact, pair: now?.pair ?? null, tier: now?.tier ?? null } }
|
|
413
1174
|
: { ...r, exp: carrier.contacts().answers.find((x) => x.did === r.did)?.exp ?? null };
|
|
@@ -427,6 +1188,46 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
427
1188
|
if (tier !== 'own' && tier !== 'friend' && tier !== 'quiet') refuse(400, 'body', 'tier: own, friend or quiet');
|
|
428
1189
|
return carrier.setTier(c.did, tier);
|
|
429
1190
|
}),
|
|
1191
|
+
'POST /api/presence': (b) => serial(async () => {
|
|
1192
|
+
const c = contactOf(b['contact']), allow = b['allow'];
|
|
1193
|
+
if (typeof allow !== 'boolean') refuse(400, 'body', 'allow: true or false');
|
|
1194
|
+
try { return carrier.setPresence(c.did, allow); } catch (e) { if (e.check === 'presence_own') e.status = 409; throw e; }
|
|
1195
|
+
}),
|
|
1196
|
+
// A contact's kind, the human's choice (Chat settings → This is an agent): agent, person, or null (the page decides again).
|
|
1197
|
+
'POST /api/kind': (b) => serial(async () => {
|
|
1198
|
+
const c = contactOf(b['contact']), k = b['kind'];
|
|
1199
|
+
if (k !== 'agent' && k !== 'person' && k !== null) refuse(400, 'body', 'kind: agent, person, or null (automatic)');
|
|
1200
|
+
if (k === null) delete data.kind[c.did]; else data.kind[c.did] = k;
|
|
1201
|
+
saveData(); changed();
|
|
1202
|
+
return { did: c.did, kind: kindOf(c, null, rosterAgents()).kind, kind_set: k !== null };
|
|
1203
|
+
}),
|
|
1204
|
+
// The keeper's settings and payment requests (UI-API.md "Keeper"): `sigelo-agent ui` answers them where the
|
|
1205
|
+
// keeper runs. Here, with hooks.computer (a computer of this operator paired to this profile, scope all;
|
|
1206
|
+
// design/agent-wallet-page.md §4), they go to that computer, and a limit is changed by a policy-change this
|
|
1207
|
+
// page signs with its own identity: the computer carries it to its keeper and cannot alter it. Without one:
|
|
1208
|
+
// elsewhere, and the writes are refused keeper_elsewhere.
|
|
1209
|
+
'GET /api/keeper': async () => {
|
|
1210
|
+
if (!PC) return { state: 'elsewhere', via: null };
|
|
1211
|
+
try { return { ...(await viaPc('GET', '/api/keeper')), via: { computer: PC.name() } }; } catch (e) { return { state: 'elsewhere', via: { computer: PC.name(), error: e.message } }; }
|
|
1212
|
+
},
|
|
1213
|
+
'POST /api/keeper/agent': async (b) => {
|
|
1214
|
+
if (!PC) return refuse(409, 'keeper_elsewhere', 'Set this on the computer that runs the keeper.');
|
|
1215
|
+
const v = await viaPc('GET', '/api/keeper'), ks = Array.isArray(v.keepers) ? v.keepers : [];
|
|
1216
|
+
const k = ks.find((x) => x.id === b['keeper']) ?? (b['keeper'] === undefined && ks.length === 1 ? ks[0] : null) ?? refuse(404, 'keeper_unknown', `no keeper ${JSON.stringify(b['keeper'])} on ${PC.name()}`);
|
|
1217
|
+
if (typeof b['agent'] !== 'string') refuse(400, 'body', 'agent: its name in the keeper');
|
|
1218
|
+
const set = Object.fromEntries(KEEPER_FIELDS.filter((f) => b[f] !== undefined).map((f) => [f, b[f]]));
|
|
1219
|
+
if (Object.keys(set).length === 0) refuse(400, 'body', `one of ${KEEPER_FIELDS.join(', ')}`);
|
|
1220
|
+
const t = nowS(), body = { v: 'sigelo/0', typ: 'policy-change', keeper: k.did, net: k.net, agent: b['agent'], set, nonce: hexOf(16), iat: t, exp: t + 300 };
|
|
1221
|
+
const idn = carrier.identity();
|
|
1222
|
+
return viaPc('POST', '/api/keeper/policy', { keeper: k.id, change: { body, sig: signAs(idn, body), bundle: idn.bundle } });
|
|
1223
|
+
},
|
|
1224
|
+
...Object.fromEntries(['approvers', 'approve', 'refuse', 'restart'].map((r) => [`POST /api/keeper/${r}`, (b) => (PC ? viaPc('POST', `/api/keeper/${r}`, b) : refuse(409, 'keeper_elsewhere', 'Set this on the computer that runs the keeper.'))])),
|
|
1225
|
+
'POST /api/keeper/policy': (b) => (PC ? viaPc('POST', '/api/keeper/policy', b) : refuse(409, 'keeper_elsewhere', 'Set this on the computer that runs the keeper.')),
|
|
1226
|
+
// The wallet (UI-API.md "Wallet"): none in this page; `sigelo-agent ui` answers these with the computer's.
|
|
1227
|
+
'GET /api/wallet': () => ({ on: data.settings.wallet === true, where: 'none' }),
|
|
1228
|
+
'GET /api/price': () => ({ on: false, currency: walletSet().currency }),
|
|
1229
|
+
...Object.fromEntries(['GET /api/wallet/history', 'GET /api/wallet/tx', 'GET /api/wallet/services', 'GET /api/wallet/nodes', 'POST /api/wallet/sync', 'POST /api/wallet/receive', 'POST /api/wallet/label',
|
|
1230
|
+
'POST /api/wallet/review', 'POST /api/wallet/send', 'POST /api/wallet/service', 'POST /api/wallet/node'].map((r) => [r, () => refuse(409, 'wallet_none', 'This phone has no wallet yet: use the computer\'s page.')])),
|
|
430
1231
|
'POST /api/tag': (b) => serial(async () => {
|
|
431
1232
|
const c = contactOf(b['contact']), tags = b['tags'];
|
|
432
1233
|
if (!Array.isArray(tags) || tags.length > 8) refuse(400, 'body', 'tags: a list of at most 8');
|
|
@@ -437,39 +1238,97 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
437
1238
|
}),
|
|
438
1239
|
'POST /api/forget': (b) => serial(async () => forget(contactOf(b['contact']))),
|
|
439
1240
|
'POST /api/send': (b) => serial(async () => {
|
|
440
|
-
const c = contactOf(b['to']),
|
|
1241
|
+
const c = contactOf(b['to']), st = b['statement'];
|
|
1242
|
+
// A signed statement (the header's): its portable text, labelled, checked before it goes.
|
|
1243
|
+
if (st !== undefined && (typeof st !== 'string' || !checkStatement(st, nowS()).valid)) refuse(400, 'statement', 'statement: the portable text of a valid signed statement (POST /api/statement/check)');
|
|
1244
|
+
// re: the n of a message of this chat that this one answers (carrier.mjs "Replies"): its label quotes it.
|
|
1245
|
+
const re = b['re'];
|
|
1246
|
+
if (re !== undefined && (st !== undefined || !Number.isSafeInteger(re))) refuse(400, 'body', 're: the n of a message of this chat (not with a statement)');
|
|
1247
|
+
const quoted = re === undefined ? null : recs.find((r) => (r.kind === 'in' || r.kind === 'out') && r.did === c.did && r.n === re && typeof r.text === 'string') ?? refuse(404, 'message', 'no such message in this chat to answer');
|
|
1248
|
+
const text = st ?? b['text'], label = st !== undefined ? STATEMENT_LABEL : quoted ? reLabel(quoted.text, quoted.kind === 'out') : '';
|
|
441
1249
|
if (typeof text !== 'string' || text.trim() === '' || text.length > TEXT_MAX) refuse(400, 'body', `text: 1 to ${TEXT_MAX} characters`);
|
|
1250
|
+
// at: before it is sealed, so a receipt naming its iat covers it (statusOf).
|
|
1251
|
+
const at = nowS(), lab = label ? { label } : {};
|
|
442
1252
|
let r;
|
|
443
|
-
try { [r] = await carrier.sendAll(c.did, [text], { label
|
|
1253
|
+
try { [r] = await carrier.sendAll(c.did, [text], { label }); } catch (e) {
|
|
444
1254
|
// The session failed: the message stays queued in the carrier and goes at a later connection.
|
|
445
1255
|
if (!/queued/.test(e.message)) throw e;
|
|
446
|
-
return record({ kind: 'out', did: c.did, id: null, text, status: 'queued', code: e.check, detail: e.message });
|
|
1256
|
+
return record({ kind: 'out', did: c.did, id: null, text, status: 'queued', code: e.check, detail: e.message, at, ...lab });
|
|
447
1257
|
}
|
|
448
|
-
return record({ kind: 'out', did: c.did, id: r.id, text, status: r.status, code: r.code, detail: r.detail });
|
|
1258
|
+
return record({ kind: 'out', did: c.did, id: r.id, text, status: r.status, code: r.code, detail: r.detail, at, ...lab });
|
|
449
1259
|
}),
|
|
1260
|
+
'GET /api/search': (_, q) => search(q),
|
|
450
1261
|
'GET /api/messages': (_, q) => {
|
|
451
|
-
const
|
|
1262
|
+
const x = contactOf(q.get('contact')), d = x.did, since = Number(q.get('since') ?? 0) || 0;
|
|
452
1263
|
const msgs = recs.filter((r) => (r.kind === 'in' || r.kind === 'out') && r.did === d && r.n > since).slice(-200);
|
|
453
|
-
//
|
|
1264
|
+
// A reply's quote (carrier.mjs "Replies"): the message it names, found among this chat's by its text and author.
|
|
1265
|
+
const all = recs.filter((r) => (r.kind === 'in' || r.kind === 'out') && r.did === d);
|
|
1266
|
+
const reOf = (r) => {
|
|
1267
|
+
const m = RE_LABEL.exec(r.label ?? '');
|
|
1268
|
+
if (!m) return null;
|
|
1269
|
+
const kind = (r.kind === 'out') === (m[2] === 's') ? 'out' : 'in';
|
|
1270
|
+
const q = all.filter((x) => x.n < r.n && x.kind === kind && typeof x.text === 'string' && quoteHash(x.text) === m[1]).at(-1);
|
|
1271
|
+
return { n: q?.n ?? null, dir: kind, text: q ? q.text.split('\n')[0].slice(0, 120) : null };
|
|
1272
|
+
};
|
|
1273
|
+
// Read: the page has shown them; a seen receipt when one is due (the header's).
|
|
454
1274
|
if ((data.read[d] ?? 0) < seq) { data.read[d] = seq; saveData(); }
|
|
455
|
-
|
|
1275
|
+
receipt(d);
|
|
1276
|
+
return { seq, messages: msgs.map((r) => ({ n: r.n, dir: r.kind, at: r.at, iat: r.iat ?? null, text: textOf(r.text), label: r.label ?? '', status: statusOf(r, x.seen_upto), code: r.code ?? null, detail: r.detail ?? null, link: r.link ?? null,
|
|
1277
|
+
...(RE_LABEL.test(r.label ?? '') && { re: reOf(r) }),
|
|
1278
|
+
...(r.label === STATEMENT_LABEL && { statement: statementOf(r) }), ...(r.photo && { photo: r.photo }), ...(r.voice && { voice: r.voice }), ...(r.file && { file: r.file }), ...(r.call && { call: r.call }),
|
|
1279
|
+
...(r.approval && { approval: r.approval }), ...(r.question && { question: r.question }) })) };
|
|
456
1280
|
},
|
|
457
1281
|
'POST /api/sync': () => serial(async () => { await carrier.sync(); return { synced: true }; }),
|
|
458
|
-
'POST /api/history/clear': () => serial(async () => {
|
|
1282
|
+
'POST /api/history/clear': (b) => serial(async () => {
|
|
1283
|
+
// One chat (contact: its messages go, the rest stays, written again), or all of it.
|
|
1284
|
+
if (b['contact'] !== undefined) {
|
|
1285
|
+
const d = contactOf(b['contact']).did, keep = recs.filter((r) => !((r.kind === 'in' || r.kind === 'out') && r.did === d));
|
|
1286
|
+
store.clearHistory();
|
|
1287
|
+
for (const r of keep) store.append(JSON.stringify(r) + '\n');
|
|
1288
|
+
recs.length = 0; outById.clear();
|
|
1289
|
+
for (const r of keep) { recs.push(r); if (r.kind === 'out' && r.id) outById.set(r.id, r); }
|
|
1290
|
+
changed();
|
|
1291
|
+
return { cleared: true, contact: d };
|
|
1292
|
+
}
|
|
459
1293
|
store.clearHistory(); recs.length = 0; outById.clear(); data.read = {}; saveData();
|
|
460
1294
|
changed();
|
|
461
1295
|
return { cleared: true };
|
|
462
1296
|
}),
|
|
1297
|
+
// Notifications for one chat (a contact's DID or a group's gid): on (the default) or off.
|
|
1298
|
+
'POST /api/notify': (b) => serial(async () => {
|
|
1299
|
+
const chat = b['chat'], on = b['on'];
|
|
1300
|
+
if (typeof on !== 'boolean') refuse(400, 'body', 'on: true or false');
|
|
1301
|
+
const isGroup = typeof chat === 'string' && G && groupsFile && G.list({ carrier, file: groupsFile }).some((g) => g.gid === chat);
|
|
1302
|
+
const id = isGroup ? chat : contactOf(chat).did;
|
|
1303
|
+
if (on) delete data.notify[id]; else data.notify[id] = false;
|
|
1304
|
+
saveData(); changed();
|
|
1305
|
+
return { chat: id, notify: on };
|
|
1306
|
+
}),
|
|
463
1307
|
// Settings: the relay new codes name (above). relay: a host[:port], or "" / null for relay.sigelo.ai.
|
|
464
|
-
'GET /api/settings': () =>
|
|
1308
|
+
'GET /api/settings': () => settingsAll(),
|
|
1309
|
+
// Any of: relay, seen_receipts, notify, new_tier, new_presence (Settings → Chats); wallet, prices, currency (Settings → Wallet); each checked before any is kept.
|
|
465
1310
|
'POST /api/settings': (b) => serial(async () => {
|
|
466
|
-
const v = b['relay'];
|
|
467
|
-
if (v === undefined) refuse(400, 'body', 'relay: a host[:port], or "" for the default');
|
|
468
|
-
|
|
469
|
-
|
|
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)');
|
|
1313
|
+
for (const k of flags) if (typeof b[k] !== 'boolean') refuse(400, 'body', `${k}: true or false`);
|
|
1314
|
+
if (t !== undefined && !TIER_NEW.has(t)) refuse(400, 'body', 'new_tier: own, friend or quiet');
|
|
1315
|
+
if (cur !== undefined && cur !== null && !CURRENCIES.includes(cur)) refuse(400, 'body', `currency: one of ${CURRENCIES.join(', ')}`);
|
|
1316
|
+
if (v === undefined) {} else if (v === null || v === '' || v === DEFAULT_RELAY) delete data.settings.relay;
|
|
1317
|
+
else if (typeof v === 'string' && goodRelay(v.trim().toLowerCase())) {
|
|
1318
|
+
data.settings.relay = v.trim().toLowerCase();
|
|
1319
|
+
data.settings.relays = [data.settings.relay, ...added().filter((x) => x !== data.settings.relay)].slice(0, ADDED_MAX);
|
|
1320
|
+
}
|
|
470
1321
|
else refuse(400, 'body', `relay: a host name, as relay.example.org (a port after a colon if not the usual)`);
|
|
1322
|
+
if (b['seen_receipts'] !== undefined) data.settings.seen = b['seen_receipts'];
|
|
1323
|
+
if (b['notify'] !== undefined) data.settings.notify = b['notify'];
|
|
1324
|
+
if (b['new_presence'] !== undefined) data.settings.new_presence = b['new_presence'];
|
|
1325
|
+
if (b['calls'] !== undefined) data.settings.calls = b['calls'];
|
|
1326
|
+
if (t !== undefined) data.settings.new_tier = t;
|
|
1327
|
+
if (b['wallet'] !== undefined) data.settings.wallet = b['wallet'];
|
|
1328
|
+
if (b['prices'] !== undefined) data.settings.prices = b['prices'];
|
|
1329
|
+
if (cur !== undefined) { if (cur === null) delete data.settings.currency; else data.settings.currency = cur; }
|
|
471
1330
|
saveData(); changed();
|
|
472
|
-
return
|
|
1331
|
+
return settingsAll();
|
|
473
1332
|
}),
|
|
474
1333
|
// The signed registry's relays (sigelo.ai/relays.json, verified; fetched at most once a day): the page's picker.
|
|
475
1334
|
'GET /api/relays': async () => ({ relays: await carrier.registryRelays() }),
|
|
@@ -484,8 +1343,12 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
484
1343
|
'POST /api/agents/enrol-code': (b) => serial(async () => {
|
|
485
1344
|
seatHere();
|
|
486
1345
|
if (!enrolFile) refuse(404, 'route', 'no enrolment here');
|
|
487
|
-
const name = b['name'], tier = b['tier'], relay = b['relay'];
|
|
1346
|
+
const name = b['name'], tier = b['tier'], relay = b['relay'], words = b['confirm_words'], label = b['operator_name'], ttl = b['ttl'];
|
|
1347
|
+
// The code's life the app picked (enrol --ttl's): 10 minutes (the default), an hour or a day.
|
|
1348
|
+
if (ttl !== undefined && ![600, 3600, 86400].includes(ttl)) refuse(400, 'body', 'ttl: 600, 3600 or 86400 seconds (10 minutes, an hour, a day)');
|
|
488
1349
|
if (typeof name !== 'string' || !AGENT_NAME.test(name)) refuse(400, 'body', 'name: lowercase letters, digits, _ and -, at most 64');
|
|
1350
|
+
if (words !== undefined && typeof words !== 'boolean') refuse(400, 'body', 'confirm_words: true or false (default false: checked by its DID)');
|
|
1351
|
+
if (label !== undefined && label !== null && label !== '' && E.operatorLabel(label) === null) refuse(400, 'body', 'operator_name: how the agent files you, 1 to 64 characters');
|
|
489
1352
|
if (tier !== undefined && tier !== 'own' && tier !== 'friend' && tier !== 'quiet') refuse(400, 'body', 'tier: own (the default), friend or quiet');
|
|
490
1353
|
if (relay !== undefined && relay !== null && relay !== '' && !(typeof relay === 'string' && goodRelay(relay.trim().toLowerCase()))) refuse(400, 'body', 'relay: a host name, as relay.example.org');
|
|
491
1354
|
const at = relayFixed ?? (typeof relay === 'string' && relay !== '' ? relay.trim().toLowerCase() : newCodes());
|
|
@@ -495,15 +1358,72 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
495
1358
|
const used = Object.keys(k.workers).map(Number), i = used.length ? Math.max(...used) + 1 : 0;
|
|
496
1359
|
const root = await K.root(k);
|
|
497
1360
|
let r;
|
|
498
|
-
try {
|
|
499
|
-
|
|
1361
|
+
try {
|
|
1362
|
+
r = await E.issue({ carrier, file: enrolFile, i, n: 0, name, keeper: root, relay: at, started: startedBy(b), confirmWords: words === true, ...(ttl !== undefined && { ttl }),
|
|
1363
|
+
...(typeof label === 'string' && label !== '' && { operatorName: label }) });
|
|
1364
|
+
} finally { root.K.fill(0); }
|
|
1365
|
+
// What this page shows of it, kept with the enrolment so a restart brings the code screen back (look()).
|
|
1366
|
+
// The code as an agent is given it: ENROL-K7F3-Q9ZP (enrol.mjs enrol_code), so it is never taken for a pairing code.
|
|
1367
|
+
const shown = r.enrol_code ?? r.short;
|
|
1368
|
+
const until = pend((x) => { const y = x.issued[r.id]; if (y) y.page = { short: shown, short_exp: r.short_exp, tier: tier ?? 'own' }; return y?.attestation?.body?.exp ?? null; });
|
|
500
1369
|
await K.update((x) => { x.workers[i] = { name, n: 0, did: r.did, original: r.original, placed: 'remote', at: nowS(), ...(until && { until }) }; });
|
|
501
1370
|
if (tier === 'friend' || tier === 'quiet') carrier.presetTier(r.original, tier);
|
|
502
|
-
const e = { id: r.id, worker: i, name, short:
|
|
1371
|
+
const e = { id: r.id, worker: i, name, short: shown, code: shown, exp: r.short_exp, relay: r.relay, tier: tier ?? 'own', state: 'code', did: r.did, original: r.original, confirmWords: words === true };
|
|
503
1372
|
enrolling.set(e.id, e);
|
|
504
1373
|
changed();
|
|
505
1374
|
return { worker: i, name, did: r.did, original: r.original, tier: e.tier, ...pub(e) };
|
|
506
1375
|
}),
|
|
1376
|
+
// The optional words switch: the human's answer for an enrolment that holds its key until it.
|
|
1377
|
+
'POST /api/agents/enrol-words': (b) => serial(async () => {
|
|
1378
|
+
const e = enrolling.get(String(b['id'])) ?? refuse(404, 'enrol', 'no such enrolment on this page');
|
|
1379
|
+
if (typeof b['match'] !== 'boolean') refuse(400, 'body', 'match: true (the agent\'s machine shows the same four words) or false');
|
|
1380
|
+
if (!LIVE.has(e.state)) refuse(409, 'enrol_state', `this enrolment is ${e.state}`);
|
|
1381
|
+
e.wordsOk = b['match'];
|
|
1382
|
+
pend((x) => { if (x.issued[e.id]) x.issued[e.id].words_ok = b['match']; });
|
|
1383
|
+
await agentRound();
|
|
1384
|
+
if (!b['match']) {
|
|
1385
|
+
pend((x) => { delete x.issued[e.id]; });
|
|
1386
|
+
await K?.update((k) => { if (k.workers[e.worker]?.name === e.name && k.workers[e.worker].placed === 'remote') delete k.workers[e.worker]; });
|
|
1387
|
+
if (e.temp) { try { await carrier.forget(e.temp); } catch {} }
|
|
1388
|
+
Object.assign(e, { state: 'failed', check: 'device_words', detail: 'The four words differed: its key was not sent, and the code is dropped. Make a new one.' });
|
|
1389
|
+
}
|
|
1390
|
+
changed();
|
|
1391
|
+
return pub(e);
|
|
1392
|
+
}),
|
|
1393
|
+
// "Try now" (design/profiles.md §6): the automatic tries paused for the day; the human's goes now.
|
|
1394
|
+
'POST /api/pow/try': (b) => serial(async () => {
|
|
1395
|
+
const r = await carrier.tryNow({ confirmed: b['pow_confirmed'] === true });
|
|
1396
|
+
live.powCapped = null; live.powConfirm = null; keepOffline(); changed();
|
|
1397
|
+
return r;
|
|
1398
|
+
}),
|
|
1399
|
+
// Cancel an enrolment in any state before it is done (0.1.17: a stale "k (enrolling)" could not be removed): the
|
|
1400
|
+
// pending entry dropped, the temporary contact forgotten, the code withdrawn. Its worker leaves the roster (the
|
|
1401
|
+
// index free again), or is marked revoked once its key may have gone (sent once, or being sent).
|
|
1402
|
+
'POST /api/agents/cancel': (b) => serial(async () => {
|
|
1403
|
+
seatHere();
|
|
1404
|
+
if (!enrolFile) refuse(404, 'route', 'no enrolment here');
|
|
1405
|
+
const id = String(b['id'] ?? ''), e = enrolling.get(id);
|
|
1406
|
+
await look();
|
|
1407
|
+
const f = pend((x) => { const y = x.issued[id]; if (y) delete x.issued[id]; if (y?.temp && x.told) delete x.told[y.temp]; return y ?? null; });
|
|
1408
|
+
if (!f && !(e && LIVE.has(e.state))) refuse(404, 'enrol', 'no such enrolment pending here (done, expired or cancelled)');
|
|
1409
|
+
if (f?.done) refuse(409, 'enrol_state', 'this enrolment is done: revoke the agent instead');
|
|
1410
|
+
if (e?.state === 'code') { try { await carrier.cancelInvite(e.code); } catch {} }
|
|
1411
|
+
const temp = e?.temp ?? f?.temp ?? carrier.answeredBy(id);
|
|
1412
|
+
if (temp) { try { await carrier.forget(temp); } catch {} }
|
|
1413
|
+
const i = e?.worker ?? f?.i, keyWent = f?.sent_at !== undefined || f?.needs_send !== undefined || e?.state === 'sending', t = nowS();
|
|
1414
|
+
let revoked = null;
|
|
1415
|
+
if (Number.isSafeInteger(i)) {
|
|
1416
|
+
await K?.update((k) => {
|
|
1417
|
+
const w = k.workers[i];
|
|
1418
|
+
if (!w || w.placed !== 'remote' || w.revoked !== undefined) return;
|
|
1419
|
+
if (keyWent) { w.revoked = t; revoked = t; } else delete k.workers[i];
|
|
1420
|
+
});
|
|
1421
|
+
}
|
|
1422
|
+
if (e) Object.assign(e, { state: 'failed', check: 'cancelled', detail: 'Cancelled: the code no longer works and nothing more is sent.' });
|
|
1423
|
+
await look();
|
|
1424
|
+
changed();
|
|
1425
|
+
return { id, worker: i ?? null, cancelled: true, revoked, forgot: temp ?? null };
|
|
1426
|
+
}),
|
|
507
1427
|
'POST /api/agents/revoke': (b) => serial(async () => {
|
|
508
1428
|
seatHere();
|
|
509
1429
|
const k = await keeperOr(), i = b['worker'], w = workerOf(k, i);
|
|
@@ -520,6 +1440,12 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
520
1440
|
return { worker: i, name: w.name, cancelled: true, revoked: null, forgot: null };
|
|
521
1441
|
}
|
|
522
1442
|
if (e && LIVE.has(e.state)) { pend((x) => { delete x.issued[e.id]; }); e.state = 'failed'; e.check = 'revoked'; if (e.temp) { try { await carrier.forget(e.temp); } catch {} } }
|
|
1443
|
+
// One made before a restart (only the pending file knows it): dropped too, its temporary contact forgotten.
|
|
1444
|
+
for (const [id, f] of [...issuedLive].filter(([, y]) => y.i === i)) {
|
|
1445
|
+
pend((x) => { delete x.issued[id]; });
|
|
1446
|
+
const temp = f.temp ?? carrier.answeredBy(id);
|
|
1447
|
+
if (temp) { try { await carrier.forget(temp); } catch {} }
|
|
1448
|
+
}
|
|
523
1449
|
const c = contactOfWorker(w);
|
|
524
1450
|
if (c) await carrier.forget(c.did);
|
|
525
1451
|
const t = nowS();
|
|
@@ -552,8 +1478,8 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
552
1478
|
};
|
|
553
1479
|
const days = b['days'];
|
|
554
1480
|
if (days !== undefined && days !== null && !Number.isSafeInteger(days)) refuse(400, 'body', 'days: whole days, 1 to 365');
|
|
555
|
-
const tierA = str('tier_a'), tierB = str('tier_b'), note_ = str('note'), relay = str('relay');
|
|
556
|
-
const rec = await L.link({ carrier, file: linksFile, a: str('a', true), b: str('b', true), purpose: str('purpose', true), ...(tierA && { tierA }), ...(tierB && { tierB }),
|
|
1481
|
+
const tierA = str('tier_a'), tierB = str('tier_b'), note_ = str('note'), relay = str('relay'), nameA = str('name_a'), nameB = str('name_b');
|
|
1482
|
+
const rec = await L.link({ carrier, file: linksFile, a: str('a', true), b: str('b', true), purpose: str('purpose', true), ...(tierA && { tierA }), ...(tierB && { tierB }), ...(nameA && { nameA }), ...(nameB && { nameB }),
|
|
557
1483
|
...(typeof days === 'number' && { days }), ...(note_ && { note: note_ }), ...(relay && { relay }) });
|
|
558
1484
|
const { code: _c, steps: _s, exp: _e, ttl: _t, ...out } = rec;
|
|
559
1485
|
return out;
|
|
@@ -593,6 +1519,26 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
593
1519
|
return { name, confirmed: match, ...(!match && { forgotten: true }) };
|
|
594
1520
|
},
|
|
595
1521
|
};
|
|
1522
|
+
// Transfers: the routes exist only where the host moves files (hooks.transfers).
|
|
1523
|
+
// Calls (UI-API.md "Calls"): the Line's routes; a person present, never an agent (agents calling: later). Every write is
|
|
1524
|
+
// refused once the seat went to another device (it would log in as you beside it).
|
|
1525
|
+
const callRouteSet = callRoutes({
|
|
1526
|
+
line, contactOf: (v) => { const x = contactOf(v); return liveContact(x.did) ?? refuse(404, 'not_contact', 'not a contact'); },
|
|
1527
|
+
callable: (c) => {
|
|
1528
|
+
if (data.kind[c.did] === 'agent' || (data.kind[c.did] !== 'person' && (c.ours === true || workerDids.has(c.did)))) return { check: 'call_agent', message: 'agents take no calls (later)' };
|
|
1529
|
+
if (c.re_pair) return { check: 'call_pairing', message: 'pair again first' };
|
|
1530
|
+
if (c.online !== true) return { check: 'call_offline', message: `${c.name} is not online now` };
|
|
1531
|
+
return true;
|
|
1532
|
+
},
|
|
1533
|
+
stun: (c) => stunOf(carrier.relay, c?.relay),
|
|
1534
|
+
can: { speaker: typeof CH.speaker === 'function', mic: typeof CH.mic === 'function', ring: typeof CH.alert === 'function' },
|
|
1535
|
+
hooks: { speaker: CH.speaker, mic: CH.mic, micSettings: CH.micSettings },
|
|
1536
|
+
allow: (c, on) => { if (on === null) delete data.calls[c.did]; else data.calls[c.did] = on; saveData(); changed(); },
|
|
1537
|
+
allowOf: (c) => canCall(c),
|
|
1538
|
+
});
|
|
1539
|
+
for (const [k, f] of Object.entries(callRouteSet)) routes[k] = k.startsWith('POST ') ? (b, q) => gone(() => f(b, q))() : f;
|
|
1540
|
+
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
|
+
if (G) Object.assign(routes, groupRoutes);
|
|
596
1542
|
// One handler for every listener: the route's answer as [status, JSON value].
|
|
597
1543
|
async function dispatch(method, url, b) {
|
|
598
1544
|
const route = routes[`${method} ${url.pathname}`];
|
|
@@ -602,8 +1548,164 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
|
|
|
602
1548
|
}
|
|
603
1549
|
}
|
|
604
1550
|
return {
|
|
605
|
-
carrier, routes, dispatch, start, halt, serial, refuse, contactOf, cleanName, record, seen, data, saveData, live, recs, linkRound, drain,
|
|
1551
|
+
carrier, routes, dispatch, start, halt, serial, refuse, contactOf, cleanName, record, seen, data, saveData, live, recs, linkRound, drain, line,
|
|
606
1552
|
setDevices: (d) => { devices = d; },
|
|
607
1553
|
onChange: (f) => { watchers.add(f); return () => watchers.delete(f); },
|
|
608
1554
|
};
|
|
609
1555
|
}
|
|
1556
|
+
|
|
1557
|
+
// ---- transfers (UI-API.md "Transfers"): the verbs of apps/contact/transfer-node.mjs over the page's session.
|
|
1558
|
+
// Refusals by check: unknown → 404; usage → 400; direct_ask, disk_full, transfer_state and the rest → 409.
|
|
1559
|
+
function transferRoutes({ X, engine, host, carrier, identity, serial, contactOf, changed, record, groups }) {
|
|
1560
|
+
const call = async (fn) => {
|
|
1561
|
+
try { const r = await fn(); changed(); return r; } catch (e) {
|
|
1562
|
+
if (e.check !== undefined && e.status === undefined) e.status = ['transfer_unknown', 'not_contact', 'group_unknown'].includes(e.check) ? 404 : ['usage', 'body', 'photo'].includes(e.check) ? 400 : 409;
|
|
1563
|
+
throw e;
|
|
1564
|
+
}
|
|
1565
|
+
};
|
|
1566
|
+
const idOf = (b) => (typeof b['id'] === 'string' && /^[0-9a-f]{32}$/.test(b['id']) ? b['id'] : refuse(400, 'body', 'id: a transfer id (32 hex digits)'));
|
|
1567
|
+
const directOf = (b) => (b['direct'] === undefined ? undefined : typeof b['direct'] === 'boolean' ? b['direct'] : refuse(400, 'body', 'direct: true or false'));
|
|
1568
|
+
const viaOf = (b) => (b['via'] === undefined || b['via'] === 'auto' || b['via'] === 'tor' ? b['via'] : refuse(400, 'body', 'via: auto or tor'));
|
|
1569
|
+
const strip = ({ file: _f, ...r }) => r;
|
|
1570
|
+
const docs = typeof host.pick === 'function';
|
|
1571
|
+
const settings = async () => ({ ...X.settings({ identity }), tor_daemon: await X.torCaps(X.torConfig()), direct_available: (await X.loadRtc()) !== null,
|
|
1572
|
+
pick: docs, camera: typeof host.photo === 'function', open: typeof host.open === 'function', voice: typeof host.rec?.keep === 'function', mic: typeof host.mic === 'function' });
|
|
1573
|
+
// A file to send: a path on this computer, or a doc picked on this phone (never both, each where it is).
|
|
1574
|
+
const sourceOf = (b) => {
|
|
1575
|
+
if (docs) return typeof b['doc'] === 'string' && b['doc'] !== '' ? { doc: b['doc'] } : refuse(400, 'body', 'doc: a file picked on this phone (POST /api/transfers/pick or /photo)');
|
|
1576
|
+
return typeof b['path'] === 'string' && b['path'] !== '' ? { path: b['path'] } : refuse(400, 'body', 'path: a file on this computer');
|
|
1577
|
+
};
|
|
1578
|
+
// A photo's preview from the page (downscaled there): {type, data, w, h}; the file's sha256, size and name are the manifest's.
|
|
1579
|
+
const shotOf = (b) => {
|
|
1580
|
+
const p = b['photo'];
|
|
1581
|
+
if (p === undefined) return null;
|
|
1582
|
+
if (typeof p !== 'object' || p === null || Array.isArray(p)) refuse(400, 'photo', 'photo: {type, data, w, h}');
|
|
1583
|
+
return { type: p['type'], data: p['data'], w: p['w'], h: p['h'] };
|
|
1584
|
+
};
|
|
1585
|
+
const full = (shot, f, name) => { try { return checkPhoto({ ...shot, sha256: f.whole, size: f.size, name }); } catch (e) { e.status = 400; throw e; } };
|
|
1586
|
+
// A voice message (voice.mjs): the recording sent in pieces first (POST /api/transfers/voice-part, rec), then send
|
|
1587
|
+
// {rec, voice: {name, type, duration_s, waveform?}}: the host keeps it as a file, which goes as a photo's full file does.
|
|
1588
|
+
const recOf = (b) => (typeof b['rec'] === 'string' && /^[0-9a-f]{32}$/.test(b['rec']) ? b['rec'] : refuse(400, 'body', 'rec: a recording id (32 hex digits)'));
|
|
1589
|
+
const voiceOf = (b) => {
|
|
1590
|
+
const v = b['voice'];
|
|
1591
|
+
if (v === undefined) return null;
|
|
1592
|
+
if (typeof v !== 'object' || v === null || Array.isArray(v) || b['rec'] === undefined || !host.rec) refuse(400, 'voice', 'voice: {name, type, duration_s, waveform?} with rec, where this host records');
|
|
1593
|
+
const x = { name: v['name'], type: v['type'], duration_s: v['duration_s'], ...(v['waveform'] !== undefined && { waveform: v['waveform'] }) };
|
|
1594
|
+
try { checkVoice({ ...x, sha256: '0'.repeat(64), size: 1 }); } catch (e) { e.status = 400; throw e; }
|
|
1595
|
+
return x;
|
|
1596
|
+
};
|
|
1597
|
+
const fullVoice = (vo, f, name) => { try { return checkVoice({ ...vo, sha256: f.whole, size: f.size, name }); } catch (e) { e.status = 400; throw e; } };
|
|
1598
|
+
const AUDIO = { webm: 'audio/webm', ogg: 'audio/ogg', m4a: 'audio/mp4' };
|
|
1599
|
+
return {
|
|
1600
|
+
'GET /api/transfers': () => X.list({ carrier, identity, engine }),
|
|
1601
|
+
'POST /api/transfers/send': (b) => serial(() => call(async () => {
|
|
1602
|
+
const vo = voiceOf(b), src = vo ? await host.rec.keep(recOf(b), vo.name) : sourceOf(b), d = directOf(b), via = viaOf(b), shot = shotOf(b);
|
|
1603
|
+
if (shot) { const p = { ...shot, sha256: '0'.repeat(64), size: 0, name: 'x' }; try { checkPhoto(p); } catch (e) { e.status = 400; throw e; } }
|
|
1604
|
+
// A group (design §10.3): one transfer per member paired with; the preview (or a line naming the file) as one group message.
|
|
1605
|
+
if (b['group'] !== undefined) {
|
|
1606
|
+
if (!groups) refuse(404, 'route', 'no groups here');
|
|
1607
|
+
const g = groups.list().find((x) => x.gid === b['group']) ?? refuse(404, 'group_unknown', `no group ${String(b['group'])} here`);
|
|
1608
|
+
const f = await X.prepare({ carrier, identity, ...src });
|
|
1609
|
+
const fan = await X.fanOut({ carrier, identity, members: g.members.filter((m) => !m.me).map((m) => ({ did: m.did, name: m.name, contact: m.contact })), f, ...(d !== undefined && { direct: d }), ...(via && { via }), group: g.gid });
|
|
1610
|
+
const name = fan.sent[0] ? X.list({ carrier, identity }).out.find((r) => r.id === fan.sent[0].id)?.name ?? f.name : f.name;
|
|
1611
|
+
const msg = await groups.G.send({ carrier, file: groups.file, group: g.gid, text: shot ? 'Photo' : vo ? 'Voice message' : `File: ${name}`, ...(shot && { photo: full(shot, f, name) }), ...(vo && { voice: fullVoice(vo, f, name) }) });
|
|
1612
|
+
void engine.kick();
|
|
1613
|
+
return { group: g.gid, mid: msg.mid, sha256: f.whole, name, size: f.size, sent: fan.sent, unpaired: fan.unpaired, failed: fan.failed };
|
|
1614
|
+
}
|
|
1615
|
+
const c = contactOf(b['to']);
|
|
1616
|
+
const f = await X.prepare({ carrier, identity, ...src });
|
|
1617
|
+
const r = await X.sendTo({ carrier, identity, to: c.did, f, ...(via && { via }), ...(d !== undefined && { direct: d }) });
|
|
1618
|
+
void engine.kick();
|
|
1619
|
+
if (shot) {
|
|
1620
|
+
// The preview beside the manifest: one more end-to-end message, into this chat at once.
|
|
1621
|
+
const ph = full(shot, f, r.name), at = Math.floor(Date.now() / 1000);
|
|
1622
|
+
let x = null;
|
|
1623
|
+
try { [x] = await carrier.sendAll(c.did, [ph], { label: PHOTO_LABEL }); } catch (e) { if (!/queued/.test(e.message)) throw e; }
|
|
1624
|
+
record({ kind: 'out', did: c.did, id: x?.id ?? null, text: 'Photo', label: PHOTO_LABEL, photo: ph, status: x?.status ?? 'queued', code: x?.code, detail: x?.detail, at });
|
|
1625
|
+
}
|
|
1626
|
+
if (!shot && !vo) {
|
|
1627
|
+
// (0.1.19) Any other file: its own bubble in this chat (name, size; the lane and state from its transfer), kept in the history.
|
|
1628
|
+
record({ kind: 'out', did: c.did, id: null, text: `File: ${r.name}`, label: FILE_LABEL, file: { name: r.name, size: r.size, sha256: r.sha256, via: null, transfer: r.id }, status: 'sent', at: Math.floor(Date.now() / 1000) });
|
|
1629
|
+
}
|
|
1630
|
+
if (vo) {
|
|
1631
|
+
// The voice message beside the manifest, as a photo's preview goes.
|
|
1632
|
+
const v = fullVoice(vo, f, r.name), at = Math.floor(Date.now() / 1000);
|
|
1633
|
+
let x = null;
|
|
1634
|
+
try { [x] = await carrier.sendAll(c.did, [v], { label: VOICE_LABEL }); } catch (e) { if (!/queued/.test(e.message)) throw e; }
|
|
1635
|
+
record({ kind: 'out', did: c.did, id: x?.id ?? null, text: 'Voice message', label: VOICE_LABEL, voice: v, status: x?.status ?? 'queued', code: x?.code, detail: x?.detail, at });
|
|
1636
|
+
}
|
|
1637
|
+
return strip(r);
|
|
1638
|
+
})),
|
|
1639
|
+
// 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
|
+
...(docs && { 'POST /api/transfers/pick': (b) => serial(async () => (await host.pick({ images: b?.['images'] === true })) ?? { cancelled: true }) }),
|
|
1642
|
+
// The microphone asked of the shell before the page records (Android: RECORD_AUDIO at the first); none elsewhere.
|
|
1643
|
+
// Refused once, never asked again (the shell remembers): mic-settings opens the app's settings page instead.
|
|
1644
|
+
...(typeof host.mic === 'function' && { 'POST /api/transfers/mic': async () => ({ granted: await host.mic() }) }),
|
|
1645
|
+
...(typeof host.micSettings === 'function' && { 'POST /api/transfers/mic-settings': async () => { await host.micSettings(); return { opened: true }; } }),
|
|
1646
|
+
...(typeof host.photo === 'function' && { 'POST /api/transfers/photo': () => serial(async () => (await host.photo({ keepLocation: X.settings({ identity }).keep_location })) ?? { cancelled: true }) }),
|
|
1647
|
+
// A recording's pieces (at most 128 KiB each, in order): into the host's file for it, kept until send names it.
|
|
1648
|
+
...(host.rec && { 'POST /api/transfers/voice-part': (b) => serial(async () => {
|
|
1649
|
+
const rec = recOf(b), off = b['offset'], data = b['data'];
|
|
1650
|
+
if (!Number.isSafeInteger(off) || off < 0 || off > VOICE_SIZE_MAX) refuse(400, 'body', 'offset: bytes from the start');
|
|
1651
|
+
if (typeof data !== 'string' || data === '' || data.length > Math.ceil((128 * 1024) / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) refuse(400, 'body', 'data: base64 of 1 byte to 128 KiB');
|
|
1652
|
+
const bytes = unb64(data);
|
|
1653
|
+
if (off + bytes.length > VOICE_SIZE_MAX) refuse(400, 'voice', `a voice message is at most ${VOICE_SIZE_MAX / 2 ** 20} MiB`);
|
|
1654
|
+
await host.rec.write(rec, off, bytes);
|
|
1655
|
+
return { rec, size: off + bytes.length };
|
|
1656
|
+
}) }),
|
|
1657
|
+
// A voice message's recording that landed here, to play: {id, type, data (base64)}.
|
|
1658
|
+
...(host.rec && { 'GET /api/transfers/audio': (_, q) => call(async () => {
|
|
1659
|
+
const id = idOf({ id: q.get('id') }), r = X.list({ carrier, identity }).in.find((x) => x.id === id) ?? refuse(404, 'transfer_unknown', 'no such file here');
|
|
1660
|
+
if (r.state !== 'done' || !r.saved) refuse(409, 'transfer_state', `${r.name} has not landed yet`);
|
|
1661
|
+
if (r.size > VOICE_SIZE_MAX) refuse(409, 'voice', 'too large for a voice message');
|
|
1662
|
+
const bytes = await host.rec.read(r.saved);
|
|
1663
|
+
return { id, type: AUDIO[/\.([a-z0-9]+)$/i.exec(r.name)?.[1]?.toLowerCase() ?? ''] ?? 'application/octet-stream', data: b64(bytes) };
|
|
1664
|
+
}) }),
|
|
1665
|
+
...(typeof host.open === 'function' && { 'POST /api/transfers/open': (b) => call(async () => {
|
|
1666
|
+
const id = idOf(b), L = X.list({ carrier, identity });
|
|
1667
|
+
// (0.1.19) A file I sent: the one picked (the record keeps it; the list leaves it out).
|
|
1668
|
+
if (L.out.some((x) => x.id === id)) {
|
|
1669
|
+
const f = engine.st((s) => (s.out[id] ? { ...s.out[id] } : null));
|
|
1670
|
+
if (!f?.file) refuse(409, 'transfer_state', 'that file is not on this device any more');
|
|
1671
|
+
await host.open(f.file, f.name);
|
|
1672
|
+
return { opened: id };
|
|
1673
|
+
}
|
|
1674
|
+
const r = L.in.find((x) => x.id === id) ?? refuse(404, 'transfer_unknown', 'no such file here');
|
|
1675
|
+
if (r.state !== 'done' || !r.saved) refuse(409, 'transfer_state', `${r.name} has not landed yet`);
|
|
1676
|
+
await host.open(r.saved, r.name);
|
|
1677
|
+
return { opened: r.id };
|
|
1678
|
+
}) }),
|
|
1679
|
+
'POST /api/transfers/auto': (b) => serial(() => call(async () => {
|
|
1680
|
+
const mb = b['mb'];
|
|
1681
|
+
if (mb !== null && (typeof mb !== 'number' || !Number.isFinite(mb))) refuse(400, 'body', 'mb: a size in MB (0: always ask), or null: the default');
|
|
1682
|
+
return X.setAuto({ carrier, identity, contact: contactOf(b['contact']).did, mb });
|
|
1683
|
+
})),
|
|
1684
|
+
'POST /api/transfers/accept': (b) => serial(() => call(async () => {
|
|
1685
|
+
const d = directOf(b), via = viaOf(b), r = X.accept({ carrier, identity, id: idOf(b), ...(via && { via }), ...(d !== undefined && { direct: d }) });
|
|
1686
|
+
void engine.kick();
|
|
1687
|
+
return r;
|
|
1688
|
+
})),
|
|
1689
|
+
'POST /api/transfers/resume': (b) => serial(() => call(async () => { const r = (X.resume ?? X.accept)({ carrier, identity, id: idOf(b), ...(directOf(b) !== undefined && { direct: directOf(b) }) }); void engine.kick(); return r; })),
|
|
1690
|
+
// (0.1.19) The sender's choices on a file that did not go: over the relay lane (at most 8 MiB), or offered afresh.
|
|
1691
|
+
'POST /api/transfers/relay': (b) => serial(() => call(async () => strip(await engine.relay(idOf(b), { manual: true })))),
|
|
1692
|
+
'POST /api/transfers/retry': (b) => serial(() => call(async () => { const r = strip(await X.retry({ carrier, identity, id: idOf(b), engine })); void engine.kick(); return r; })),
|
|
1693
|
+
'POST /api/transfers/decline': (b) => serial(() => call(async () => X.decline({ carrier, identity, id: idOf(b) }))),
|
|
1694
|
+
'POST /api/transfers/cancel': (b) => serial(() => call(async () => strip(await X.cancel({ carrier, identity, id: idOf(b), engine })))),
|
|
1695
|
+
'POST /api/transfers/forget': (b) => serial(() => call(async () => strip(X.forget({ carrier, identity, id: idOf(b), engine })))),
|
|
1696
|
+
'POST /api/transfers/direct': (b) => serial(() => call(async () => {
|
|
1697
|
+
if (typeof b['on'] !== 'boolean') refuse(400, 'body', 'on: true or false');
|
|
1698
|
+
return X.setDirect({ carrier, identity, contact: contactOf(b['contact']).did, on: b['on'] });
|
|
1699
|
+
})),
|
|
1700
|
+
'GET /api/transfers/settings': () => settings(),
|
|
1701
|
+
'POST /api/transfers/settings': (b) => serial(() => call(async () => {
|
|
1702
|
+
const patch = {};
|
|
1703
|
+
if (b['tor'] !== undefined) { if (typeof b['tor'] !== 'boolean') refuse(400, 'body', 'tor: true or false'); patch.tor = b['tor']; }
|
|
1704
|
+
if (b['prefer'] !== undefined) { if (b['prefer'] !== 'fast' && b['prefer'] !== 'private') refuse(400, 'body', 'prefer: fast or private'); patch.prefer = b['prefer']; }
|
|
1705
|
+
if (b['auto_mb'] !== undefined) { if (typeof b['auto_mb'] !== 'number' || !Number.isFinite(b['auto_mb']) || b['auto_mb'] < 0) refuse(400, 'body', 'auto_mb: a size in MB, 0: always ask'); patch.auto_mb = b['auto_mb']; }
|
|
1706
|
+
if (b['keep_location'] !== undefined) { if (typeof b['keep_location'] !== 'boolean') refuse(400, 'body', 'keep_location: true or false'); patch.keep_location = b['keep_location']; }
|
|
1707
|
+
X.settings({ identity, patch });
|
|
1708
|
+
return settings();
|
|
1709
|
+
})),
|
|
1710
|
+
};
|
|
1711
|
+
}
|