@fleetmesh/leaf 0.0.0-stage → 0.1.0

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.
Files changed (59) hide show
  1. package/README.md +103 -2
  2. package/dist/constants.d.ts +27 -0
  3. package/dist/constants.js +32 -0
  4. package/dist/descriptor.d.ts +29 -0
  5. package/dist/descriptor.js +73 -0
  6. package/dist/did.d.ts +59 -0
  7. package/dist/did.js +221 -0
  8. package/dist/didcomm.d.ts +59 -0
  9. package/dist/didcomm.js +176 -0
  10. package/dist/encoding.d.ts +14 -0
  11. package/dist/encoding.js +68 -0
  12. package/dist/event.d.ts +22 -0
  13. package/dist/event.js +42 -0
  14. package/dist/giftwrap.d.ts +29 -0
  15. package/dist/giftwrap.js +100 -0
  16. package/dist/index.d.ts +17 -0
  17. package/dist/index.js +20 -0
  18. package/dist/keys.d.ts +6 -0
  19. package/dist/keys.js +31 -0
  20. package/dist/mediation/leaf.d.ts +121 -0
  21. package/dist/mediation/leaf.js +238 -0
  22. package/dist/mediation/messages.d.ts +96 -0
  23. package/dist/mediation/messages.js +79 -0
  24. package/dist/negentropy.d.ts +81 -0
  25. package/dist/negentropy.js +352 -0
  26. package/dist/nip44.d.ts +18 -0
  27. package/dist/nip44.js +119 -0
  28. package/dist/pwa/browser-leaf.d.ts +15 -0
  29. package/dist/pwa/browser-leaf.js +91 -0
  30. package/dist/pwa/hub.d.ts +51 -0
  31. package/dist/pwa/hub.js +137 -0
  32. package/dist/pwa/store.d.ts +39 -0
  33. package/dist/pwa/store.js +157 -0
  34. package/dist/relay.d.ts +67 -0
  35. package/dist/relay.js +232 -0
  36. package/dist/seal.d.ts +56 -0
  37. package/dist/seal.js +146 -0
  38. package/dist/session.d.ts +75 -0
  39. package/dist/session.js +230 -0
  40. package/package.json +45 -4
  41. package/src/constants.ts +36 -0
  42. package/src/descriptor.ts +88 -0
  43. package/src/did.ts +222 -0
  44. package/src/didcomm.ts +196 -0
  45. package/src/encoding.ts +67 -0
  46. package/src/event.ts +56 -0
  47. package/src/giftwrap.ts +108 -0
  48. package/src/index.ts +20 -0
  49. package/src/keys.ts +33 -0
  50. package/src/mediation/leaf.ts +292 -0
  51. package/src/mediation/messages.ts +124 -0
  52. package/src/negentropy.ts +357 -0
  53. package/src/nip44.ts +110 -0
  54. package/src/pwa/browser-leaf.ts +99 -0
  55. package/src/pwa/hub.ts +173 -0
  56. package/src/pwa/store.ts +173 -0
  57. package/src/relay.ts +273 -0
  58. package/src/seal.ts +154 -0
  59. package/src/session.ts +255 -0
@@ -0,0 +1,238 @@
1
+ // The leaf side of mediation (meshnode node/planes/transport/mediation/leaf.py,
2
+ // MobileLeafClient), widened to everything the anchor's MediatorService
3
+ // answers: admission, keylist updates, and pickup.
4
+ //
5
+ // A leaf has no inbound listener. Its address is its mediator: the anchor
6
+ // holds forwarded envelopes until the leaf connects and drains them. The
7
+ // anchor cannot read them - each inner envelope is encrypted to the leaf's
8
+ // #agree key - but it sees sizes and timing, which is why a leaf SHOULD hold
9
+ // two mediators run by different operators.
10
+ //
11
+ // Everything here builds or consumes plaintext DIDComm messages. Sealing them
12
+ // (authcrypt, then a gift wrap to the mediator's node key) and carrying them
13
+ // over the wss:// connection is the session's job, not this module's.
14
+ import { randomBytes } from '@noble/curves/utils.js';
15
+ import * as didcomm from '../didcomm.js';
16
+ import { bytesToHex } from '../encoding.js';
17
+ import { verifyEvent } from '../event.js';
18
+ import { KEYLIST_UPDATE_RESPONSE, makeForward, makeKeylistUpdate, makeMediateRequest, makePickupDeliveryRequest, makePickupMessagesReceived, MEDIATE_DENY, MEDIATE_GRANT, PICKUP_DELIVERY, PICKUP_LIMIT_DEFAULT, } from './messages.js';
19
+ /** NIP-66 / kind 11801 query a leaf with no peers sends to bootstrap relays. */
20
+ export const DESCRIPTOR_KIND = 11801;
21
+ export const COLD_START_FILTER = { kinds: [DESCRIPTOR_KIND], '#c': ['mediator'] };
22
+ export class MediationError extends Error {
23
+ }
24
+ const first = (tags, name) => tags.find((t) => t[0] === name)?.[1];
25
+ /** Select independent mediator anchors from kind 11801 descriptors, in the
26
+ * order given (the Three-Layer Operator Independence Model): each carries
27
+ * ['c', 'mediator'] and a WebSocket endpoint, and, by default, no two share
28
+ * an operator. */
29
+ export function discoverMediators(descriptors, opts = {}) {
30
+ const { requiredCount = 2, requireDistinctOperators = true, verify = true, now, allowInsecure = false } = opts;
31
+ const schemes = allowInsecure ? ['wss', 'ws'] : ['wss'];
32
+ const selected = [];
33
+ const operators = new Set(), anchors = new Set();
34
+ for (const ev of descriptors) {
35
+ if (selected.length >= requiredCount)
36
+ break;
37
+ if (!ev || ev.kind !== DESCRIPTOR_KIND || !Array.isArray(ev.tags))
38
+ continue;
39
+ if (!ev.tags.some((t) => t[0] === 'c' && t[1] === 'mediator'))
40
+ continue;
41
+ const eps = ev.tags.filter((t) => t[0] === 'endpoint' && schemes.includes(t[1]) && typeof t[2] === 'string')
42
+ .sort((a, b) => (a.length > 3 ? +a[3] : 50) - (b.length > 3 ? +b[3] : 50));
43
+ if (!eps.length)
44
+ continue;
45
+ if (verify && !verifyEvent(ev))
46
+ continue;
47
+ const exp = first(ev.tags, 'expiration');
48
+ if (now !== undefined && exp !== undefined && /^\d+$/.test(exp) && now >= +exp)
49
+ continue;
50
+ if (anchors.has(ev.pubkey))
51
+ continue;
52
+ const operator = first(ev.tags, 'operator') || ev.pubkey;
53
+ if (requireDistinctOperators && operators.has(operator))
54
+ continue;
55
+ operators.add(operator);
56
+ anchors.add(ev.pubkey);
57
+ selected.push({ descriptor: ev, did: 'did:nostr:' + ev.pubkey, endpoint: eps[0][2], operator });
58
+ }
59
+ return selected;
60
+ }
61
+ /** One leaf's mediation state across its mediators. */
62
+ export class LeafClient {
63
+ did;
64
+ kid;
65
+ mediators = new Map();
66
+ denied = new Map();
67
+ /** Recipient keys registered with each mediator. The anchor registers the
68
+ * leaf's own DID on admission; keylist updates add and remove the rest. */
69
+ keylists = new Map();
70
+ keys;
71
+ pending = new Map();
72
+ clock;
73
+ constructor(keys, clock = () => Math.floor(Date.now() / 1000)) {
74
+ this.keys = keys;
75
+ this.did = 'did:nostr:' + keys.nodePk;
76
+ this.kid = this.did + '#agree';
77
+ this.clock = clock;
78
+ }
79
+ track(msg, p) {
80
+ this.pending.set(msg.id, p);
81
+ return msg;
82
+ }
83
+ /** The pending request a response answers: by thid, from the mediator it was sent to. */
84
+ answering(msg, kinds) {
85
+ const p = this.pending.get(msg.thid);
86
+ if (!p || !kinds.includes(p.kind))
87
+ throw new MediationError(`unsolicited ${msg.type.split('/').pop()} (thid ${msg.thid})`);
88
+ if (msg.from !== p.mediator)
89
+ throw new MediationError(`answer to ${msg.thid} came from ${msg.from}, not ${p.mediator}`);
90
+ if (!Array.isArray(msg.to) || !msg.to.includes(this.did))
91
+ throw new MediationError('answer is not addressed to this leaf');
92
+ this.pending.delete(msg.thid);
93
+ return p;
94
+ }
95
+ isGranted = (mediatorDid) => this.mediators.has(mediatorDid);
96
+ /** Grants, denials and keylists, for storage. Pending requests are not
97
+ * kept: an answer to a request from a previous launch is unsolicited. */
98
+ snapshot() {
99
+ return {
100
+ mediators: [...this.mediators].map(([k, v]) => [k, { ...v, routing_keys: [...v.routing_keys] }]),
101
+ denied: [...this.denied],
102
+ keylists: [...this.keylists].map(([k, v]) => [k, [...v]]),
103
+ };
104
+ }
105
+ /** Replace this client's state with a snapshot. */
106
+ restore(state) {
107
+ this.mediators.clear();
108
+ this.denied.clear();
109
+ this.keylists.clear();
110
+ for (const [k, v] of state.mediators ?? [])
111
+ this.mediators.set(k, { ...v, routing_keys: [...v.routing_keys] });
112
+ for (const [k, v] of state.denied ?? [])
113
+ this.denied.set(k, v);
114
+ for (const [k, v] of state.keylists ?? [])
115
+ this.keylists.set(k, new Set(v));
116
+ }
117
+ // ---- admission --------------------------------------------------------
118
+ buildMediateRequest(mediatorDid) {
119
+ return this.track(makeMediateRequest(this.did, mediatorDid), { kind: 'mediate', mediator: mediatorDid });
120
+ }
121
+ /** A mediate-grant or mediate-deny answering one of this leaf's requests. */
122
+ recordMediationResponse(msg) {
123
+ if (msg.type !== MEDIATE_GRANT && msg.type !== MEDIATE_DENY)
124
+ throw new MediationError('not a mediation response: ' + msg.type);
125
+ const { mediator } = this.answering(msg, ['mediate']);
126
+ if (msg.type === MEDIATE_DENY) {
127
+ this.denied.set(mediator, String(msg.body.reason ?? ''));
128
+ return 'denied';
129
+ }
130
+ const body = msg.body;
131
+ if (!Array.isArray(body.routing_keys) || !body.routing_keys.every((k) => typeof k === 'string'))
132
+ throw new MediationError('a grant carries routing_keys');
133
+ this.mediators.set(mediator, {
134
+ routing_keys: [...body.routing_keys],
135
+ endpoint: typeof body.endpoint === 'string' ? body.endpoint : null,
136
+ granted_at: this.clock(),
137
+ });
138
+ this.denied.delete(mediator);
139
+ this.keylists.set(mediator, new Set([this.did]));
140
+ return 'granted';
141
+ }
142
+ // ---- keylist ----------------------------------------------------------
143
+ buildKeylistUpdate(mediatorDid, add = [], remove = []) {
144
+ this.requireGrant(mediatorDid);
145
+ const updates = [
146
+ ...add.map((k) => ({ recipient_key: k, action: 'add' })),
147
+ ...remove.map((k) => ({ recipient_key: k, action: 'remove' })),
148
+ ];
149
+ if (!updates.length)
150
+ throw new MediationError('a keylist update needs at least one key');
151
+ return this.track(makeKeylistUpdate(this.did, mediatorDid, updates), { kind: 'keylist', mediator: mediatorDid, updates });
152
+ }
153
+ /** Apply what the mediator says it did; a key it did not mention is unchanged. */
154
+ recordKeylistUpdateResponse(msg) {
155
+ if (msg.type !== KEYLIST_UPDATE_RESPONSE)
156
+ throw new MediationError('not a keylist-update-response: ' + msg.type);
157
+ const { mediator, updates = [] } = this.answering(msg, ['keylist']);
158
+ const asked = new Set(updates.map((u) => u.action + ' ' + u.recipient_key));
159
+ const keys = this.keylists.get(mediator) ?? new Set();
160
+ const updated = Array.isArray(msg.body?.updated) ? msg.body.updated : [];
161
+ for (const u of updated) {
162
+ // A result for a key this leaf never asked about changes nothing.
163
+ if (!asked.has(u.action + ' ' + u.recipient_key))
164
+ continue;
165
+ if (u.action === 'add' && u.result === 'success')
166
+ keys.add(u.recipient_key);
167
+ if (u.action === 'remove' && (u.result === 'success' || u.result === 'no_change'))
168
+ keys.delete(u.recipient_key);
169
+ }
170
+ this.keylists.set(mediator, keys);
171
+ return updated;
172
+ }
173
+ // ---- pickup -----------------------------------------------------------
174
+ buildDeliveryRequest(mediatorDid, limit = PICKUP_LIMIT_DEFAULT, recipientKey) {
175
+ this.requireGrant(mediatorDid);
176
+ return this.track(makePickupDeliveryRequest(this.did, mediatorDid, limit, recipientKey), { kind: 'pickup', mediator: mediatorDid });
177
+ }
178
+ /** One delivery-request per recipient key registered with this mediator.
179
+ * meshnode's MediatorService narrows an unnamed drain to the leaf's own DID
180
+ * (its default target is always in the keylist), so mail sent to any other
181
+ * registered key only comes out when that key is named. Asking per key
182
+ * drains everything from that anchor, and from one that reads an unnamed
183
+ * drain as all keys. */
184
+ buildDeliveryRequests(mediatorDid, limit = PICKUP_LIMIT_DEFAULT) {
185
+ this.requireGrant(mediatorDid);
186
+ const keys = [...(this.keylists.get(mediatorDid) ?? [this.did])];
187
+ return keys.map((k) => this.buildDeliveryRequest(mediatorDid, limit, k === this.did ? undefined : k));
188
+ }
189
+ /** Open a delivery: every attachment's inner JWE, addressed to this leaf's
190
+ * #agree key. resolveSender maps an authcrypt skid to that sender's X25519
191
+ * key; without it only anoncrypt envelopes open. */
192
+ openDelivery(msg, resolveSender) {
193
+ if (msg.type !== PICKUP_DELIVERY)
194
+ throw new MediationError('not a pickup delivery: ' + msg.type);
195
+ this.answering(msg, ['pickup']);
196
+ const rows = Array.isArray(msg.body?.messages) ? msg.body.messages : [];
197
+ return rows.filter((r) => r && typeof r.id === 'string').map((r) => {
198
+ const out = { id: r.id, sender: r.sender ?? '', recipient_key: r.recipient_key ?? '', enqueued_at: r.enqueued_at ?? 0, envelopes: [], errors: [] };
199
+ for (const att of Array.isArray(r.attachments) ? r.attachments : []) {
200
+ const name = typeof att?.id === 'string' ? att.id : '';
201
+ try {
202
+ const jwe = att?.data?.json;
203
+ if (!jwe || typeof jwe !== 'object')
204
+ throw new MediationError('attachment carries no JSON envelope');
205
+ const [message, skid] = didcomm.decrypt(jwe, this.kid, this.keys.agreementSk, resolveSender);
206
+ const from = message && typeof message === 'object' ? message.from : undefined;
207
+ if (typeof from === 'string') {
208
+ if (skid === null || from !== skid.split('#')[0]) {
209
+ throw new MediationError('inner message.from does not match authenticated skid');
210
+ }
211
+ }
212
+ out.envelopes.push({ attachment: name, message, skid });
213
+ }
214
+ catch (e) {
215
+ out.errors.push({ attachment: name, error: e.message });
216
+ }
217
+ }
218
+ return out;
219
+ });
220
+ }
221
+ /** messages-received for a drained batch, so the mediator purges it. */
222
+ buildMessagesReceived(mediatorDid, ids) {
223
+ this.requireGrant(mediatorDid);
224
+ return makePickupMessagesReceived(this.did, mediatorDid, ids);
225
+ }
226
+ // ---- sending through another leaf's mediator --------------------------
227
+ /** Wrap an inner encrypted envelope in a routing/2.0 forward to the
228
+ * recipient leaf's mediator. */
229
+ wrapForward(innerEnvelope, mediatorDid, recipientLeafDid) {
230
+ const json = typeof innerEnvelope === 'string' ? JSON.parse(innerEnvelope) : innerEnvelope;
231
+ const attachment = { id: 'att-' + bytesToHex(randomBytes(8)), data: { json } };
232
+ return makeForward(this.did, mediatorDid, recipientLeafDid, [attachment]);
233
+ }
234
+ requireGrant(mediatorDid) {
235
+ if (!this.mediators.has(mediatorDid))
236
+ throw new MediationError('no mediation grant from ' + mediatorDid);
237
+ }
238
+ }
@@ -0,0 +1,96 @@
1
+ export declare const MEDIATE_REQUEST = "https://didcomm.org/coordinate-mediation/2.0/mediate-request";
2
+ export declare const MEDIATE_GRANT = "https://didcomm.org/coordinate-mediation/2.0/mediate-grant";
3
+ export declare const MEDIATE_DENY = "https://didcomm.org/coordinate-mediation/2.0/mediate-deny";
4
+ export declare const KEYLIST_UPDATE = "https://didcomm.org/coordinate-mediation/2.0/keylist-update";
5
+ export declare const KEYLIST_UPDATE_RESPONSE = "https://didcomm.org/coordinate-mediation/2.0/keylist-update-response";
6
+ export declare const KEYLIST_QUERY = "https://didcomm.org/coordinate-mediation/2.0/keylist-query";
7
+ export declare const KEYLIST_RESPONSE = "https://didcomm.org/coordinate-mediation/2.0/keylist-response";
8
+ export declare const ROUTING_FORWARD = "https://didcomm.org/routing/2.0/forward";
9
+ export declare const PICKUP_STATUS_REQUEST = "https://didcomm.org/messagepickup/2.0/status-request";
10
+ export declare const PICKUP_STATUS = "https://didcomm.org/messagepickup/2.0/status";
11
+ export declare const PICKUP_DELIVERY_REQUEST = "https://didcomm.org/messagepickup/2.0/delivery-request";
12
+ export declare const PICKUP_DELIVERY = "https://didcomm.org/messagepickup/2.0/delivery";
13
+ export declare const PICKUP_MESSAGES_RECEIVED = "https://didcomm.org/messagepickup/2.0/messages-received";
14
+ export declare const PIURIS: readonly ['https://didcomm.org/coordinate-mediation/2.0', 'https://didcomm.org/routing/2.0', 'https://didcomm.org/messagepickup/2.0'];
15
+ export declare const PICKUP_LIMIT_MIN = 1;
16
+ export declare const PICKUP_LIMIT_MAX = 100;
17
+ export declare const PICKUP_LIMIT_DEFAULT = 10;
18
+ /** `limit` as an int in [MIN, MAX], the way the anchor reads it. */
19
+ export declare function clampPickupLimit(raw: unknown): number;
20
+ export interface Message<B = Record<string, unknown>> {
21
+ id: string;
22
+ type: string;
23
+ from: string;
24
+ to: string[];
25
+ thid: string;
26
+ body: B;
27
+ attachments?: Attachment[];
28
+ }
29
+ export interface Attachment {
30
+ id: string;
31
+ data: {
32
+ json: unknown;
33
+ };
34
+ }
35
+ export interface MediateGrantBody {
36
+ routing_keys: string[];
37
+ endpoint?: string;
38
+ }
39
+ export interface MediateDenyBody {
40
+ reason: string;
41
+ }
42
+ export type KeylistAction = 'add' | 'remove';
43
+ export interface KeylistUpdate {
44
+ recipient_key: string;
45
+ action: KeylistAction;
46
+ }
47
+ export interface KeylistUpdated extends KeylistUpdate {
48
+ result: string;
49
+ }
50
+ export interface KeylistUpdateBody {
51
+ updates: KeylistUpdate[];
52
+ }
53
+ export interface KeylistUpdateResponseBody {
54
+ updated: KeylistUpdated[];
55
+ }
56
+ export interface ForwardBody {
57
+ next: string;
58
+ }
59
+ export interface PickupStatusRequestBody {
60
+ recipient_key?: string;
61
+ }
62
+ export interface PickupStatusBody {
63
+ message_count: number;
64
+ recipient_key?: string;
65
+ }
66
+ export interface PickupDeliveryRequestBody {
67
+ limit: number;
68
+ recipient_key?: string;
69
+ }
70
+ /** What the anchor puts in a delivery: one row of its inbox. */
71
+ export interface DeliveredMessage {
72
+ id: string;
73
+ recipient_key: string;
74
+ sender: string;
75
+ attachments: Attachment[];
76
+ enqueued_at: number;
77
+ }
78
+ export interface PickupDeliveryBody {
79
+ messages: DeliveredMessage[];
80
+ recipient_key?: string;
81
+ }
82
+ export interface PickupMessagesReceivedBody {
83
+ message_id_list: string[];
84
+ }
85
+ export declare const makeMediateRequest: (from: string, to: string, thid?: string) => Message<Record<string, never>>;
86
+ export declare function makeMediateGrant(from: string, to: string, routingKeys: string[], endpoint?: string, thid?: string): Message<MediateGrantBody>;
87
+ export declare const makeMediateDeny: (from: string, to: string, reason?: string, thid?: string) => Message<MediateDenyBody>;
88
+ export declare const makeKeylistUpdate: (from: string, to: string, updates: KeylistUpdate[], thid?: string) => Message<KeylistUpdateBody>;
89
+ export declare const makeKeylistUpdateResponse: (from: string, to: string, updated: KeylistUpdated[], thid?: string) => Message<KeylistUpdateResponseBody>;
90
+ /** routing/2.0 forward wrapping inner encrypted envelopes as attachments. */
91
+ export declare function makeForward(from: string, to: string, next: string, attachments: Attachment[], thid?: string): Message<ForwardBody>;
92
+ export declare function makePickupStatusRequest(from: string, to: string, recipientKey?: string, thid?: string): Message<PickupStatusRequestBody>;
93
+ export declare function makePickupStatus(from: string, to: string, messageCount?: number, recipientKey?: string, thid?: string): Message<PickupStatusBody>;
94
+ export declare function makePickupDeliveryRequest(from: string, to: string, limit?: number, recipientKey?: string, thid?: string): Message<PickupDeliveryRequestBody>;
95
+ export declare function makePickupDelivery(from: string, to: string, messages: DeliveredMessage[], recipientKey?: string, thid?: string): Message<PickupDeliveryBody>;
96
+ export declare const makePickupMessagesReceived: (from: string, to: string, ids: string[], thid?: string) => Message<PickupMessagesReceivedBody>;
@@ -0,0 +1,79 @@
1
+ // The mediation wire (meshnode node/planes/transport/mediation/messages.py):
2
+ // PIURIs, bounds, and constructors for every coordinate-mediation/2.0,
3
+ // routing/2.0 and messagepickup/2.0 message. No storage, no I/O: the
4
+ // vocabulary the anchor and the leaf both speak.
5
+ import { randomBytes } from '@noble/curves/utils.js';
6
+ import { bytesToHex } from '../encoding.js';
7
+ export const MEDIATE_REQUEST = 'https://didcomm.org/coordinate-mediation/2.0/mediate-request';
8
+ export const MEDIATE_GRANT = 'https://didcomm.org/coordinate-mediation/2.0/mediate-grant';
9
+ export const MEDIATE_DENY = 'https://didcomm.org/coordinate-mediation/2.0/mediate-deny';
10
+ export const KEYLIST_UPDATE = 'https://didcomm.org/coordinate-mediation/2.0/keylist-update';
11
+ export const KEYLIST_UPDATE_RESPONSE = 'https://didcomm.org/coordinate-mediation/2.0/keylist-update-response';
12
+ export const KEYLIST_QUERY = 'https://didcomm.org/coordinate-mediation/2.0/keylist-query';
13
+ export const KEYLIST_RESPONSE = 'https://didcomm.org/coordinate-mediation/2.0/keylist-response';
14
+ export const ROUTING_FORWARD = 'https://didcomm.org/routing/2.0/forward';
15
+ export const PICKUP_STATUS_REQUEST = 'https://didcomm.org/messagepickup/2.0/status-request';
16
+ export const PICKUP_STATUS = 'https://didcomm.org/messagepickup/2.0/status';
17
+ export const PICKUP_DELIVERY_REQUEST = 'https://didcomm.org/messagepickup/2.0/delivery-request';
18
+ export const PICKUP_DELIVERY = 'https://didcomm.org/messagepickup/2.0/delivery';
19
+ export const PICKUP_MESSAGES_RECEIVED = 'https://didcomm.org/messagepickup/2.0/messages-received';
20
+ export const PIURIS = [
21
+ 'https://didcomm.org/coordinate-mediation/2.0',
22
+ 'https://didcomm.org/routing/2.0',
23
+ 'https://didcomm.org/messagepickup/2.0',
24
+ ];
25
+ // One drain per delivery-request, between one message and this many. The
26
+ // anchor clamps whatever it is sent; the leaf asks within bounds.
27
+ export const PICKUP_LIMIT_MIN = 1;
28
+ export const PICKUP_LIMIT_MAX = 100;
29
+ export const PICKUP_LIMIT_DEFAULT = 10;
30
+ /** `limit` as an int in [MIN, MAX], the way the anchor reads it. */
31
+ export function clampPickupLimit(raw) {
32
+ const n = typeof raw === 'number' && Number.isFinite(raw) ? Math.trunc(raw)
33
+ : typeof raw === 'string' && /^\s*[+-]?\d+\s*$/.test(raw) ? parseInt(raw, 10) : PICKUP_LIMIT_DEFAULT;
34
+ return Math.max(PICKUP_LIMIT_MIN, Math.min(PICKUP_LIMIT_MAX, n));
35
+ }
36
+ const newId = (prefix) => prefix + bytesToHex(randomBytes(8));
37
+ function make(prefix, type, from, to, body, thid) {
38
+ const id = newId(prefix);
39
+ return { id, type, from, to: [to], thid: thid ?? id, body };
40
+ }
41
+ export const makeMediateRequest = (from, to, thid) => make('med-req-', MEDIATE_REQUEST, from, to, {}, thid);
42
+ export function makeMediateGrant(from, to, routingKeys, endpoint, thid) {
43
+ const body = { routing_keys: [...routingKeys] };
44
+ if (endpoint)
45
+ body.endpoint = endpoint;
46
+ return make('med-grant-', MEDIATE_GRANT, from, to, body, thid);
47
+ }
48
+ export const makeMediateDeny = (from, to, reason = 'capacity', thid) => make('med-deny-', MEDIATE_DENY, from, to, { reason }, thid);
49
+ export const makeKeylistUpdate = (from, to, updates, thid) => make('kl-upd-', KEYLIST_UPDATE, from, to, { updates: [...updates] }, thid);
50
+ export const makeKeylistUpdateResponse = (from, to, updated, thid) => make('kl-resp-', KEYLIST_UPDATE_RESPONSE, from, to, { updated: [...updated] }, thid);
51
+ /** routing/2.0 forward wrapping inner encrypted envelopes as attachments. */
52
+ export function makeForward(from, to, next, attachments, thid) {
53
+ return { ...make('fwd-', ROUTING_FORWARD, from, to, { next }, thid), attachments: [...attachments] };
54
+ }
55
+ export function makePickupStatusRequest(from, to, recipientKey, thid) {
56
+ const body = {};
57
+ if (recipientKey)
58
+ body.recipient_key = recipientKey;
59
+ return make('pck-req-', PICKUP_STATUS_REQUEST, from, to, body, thid);
60
+ }
61
+ export function makePickupStatus(from, to, messageCount = 0, recipientKey, thid) {
62
+ const body = { message_count: messageCount };
63
+ if (recipientKey)
64
+ body.recipient_key = recipientKey;
65
+ return make('pck-stat-', PICKUP_STATUS, from, to, body, thid);
66
+ }
67
+ export function makePickupDeliveryRequest(from, to, limit = PICKUP_LIMIT_DEFAULT, recipientKey, thid) {
68
+ const body = { limit };
69
+ if (recipientKey)
70
+ body.recipient_key = recipientKey;
71
+ return make('pck-del-req-', PICKUP_DELIVERY_REQUEST, from, to, body, thid);
72
+ }
73
+ export function makePickupDelivery(from, to, messages, recipientKey, thid) {
74
+ const body = { messages: [...messages] };
75
+ if (recipientKey)
76
+ body.recipient_key = recipientKey;
77
+ return make('pck-del-', PICKUP_DELIVERY, from, to, body, thid);
78
+ }
79
+ export const makePickupMessagesReceived = (from, to, ids, thid) => make('pck-ack-', PICKUP_MESSAGES_RECEIVED, from, to, { message_id_list: [...ids] }, thid);
@@ -0,0 +1,81 @@
1
+ export declare const VERSION = 97;
2
+ export declare const VERSION_MIN = 96;
3
+ export declare const VERSION_MAX = 111;
4
+ export declare const INFINITY: bigint;
5
+ export declare const FINGERPRINT_BYTES = 16;
6
+ export declare const ID_BYTES = 32;
7
+ export declare const SKIP = 0, FINGERPRINT = 1, ID_LIST = 2;
8
+ export type Mode = typeof SKIP | typeof FINGERPRINT | typeof ID_LIST;
9
+ export declare const BUCKETS = 16;
10
+ export declare const LIST_THRESHOLD: number;
11
+ /** [timestamp, id hex]. Timestamps are unix seconds, so a number. */
12
+ export type Item = [number, string];
13
+ export declare class Malformed extends Error {
14
+ }
15
+ /** Not an error on the wire: a server answers it with the version it speaks. */
16
+ export declare class UnsupportedVersion extends Error {
17
+ readonly version: number;
18
+ constructor(version: number);
19
+ }
20
+ /** Base-128, most significant digit first, high bit on all but the last. */
21
+ export declare function encodeVarint(n: bigint | number): Uint8Array;
22
+ export declare function decodeVarint(buf: Uint8Array, i: number): [bigint, number];
23
+ /** SHA256(sum of ids as 32-byte little-endian uints mod 2^256 || varint(count))[:16]. */
24
+ export declare function fingerprintOf(ids: Iterable<Uint8Array>): Uint8Array;
25
+ /** The hex fingerprint of hex ids, as replication.fingerprint spells it. */
26
+ export declare const fingerprint: (ids: Iterable<string>) => string;
27
+ /** An exclusive upper bound: a timestamp and a disambiguating id prefix.
28
+ * Omitted trailing prefix bytes are zero. */
29
+ export interface Bound {
30
+ timestamp: bigint;
31
+ prefix: Uint8Array;
32
+ }
33
+ export declare const bound: (timestamp: bigint | number, prefix?: Uint8Array) => Bound;
34
+ /** The shortest bound separating two adjacent items: no prefix when the
35
+ * timestamps differ, else their common prefix plus one byte. */
36
+ export declare function minimalBound(prev: Item | null, item: Item): Bound;
37
+ export type Range = {
38
+ upper: Bound;
39
+ mode: typeof SKIP;
40
+ } | {
41
+ upper: Bound;
42
+ mode: typeof FINGERPRINT;
43
+ payload: Uint8Array;
44
+ } | {
45
+ upper: Bound;
46
+ mode: typeof ID_LIST;
47
+ payload: string[];
48
+ };
49
+ export declare function encodeMessage(ranges: Range[]): Uint8Array;
50
+ /** Bytes to ranges, or an exception; never a partial parse. A bound after
51
+ * infinity is normalised to infinity, as the reference does. */
52
+ export declare function decodeMessage(buf: Uint8Array): Range[];
53
+ /** One side of a reconciliation over items sorted by (timestamp, id). */
54
+ export declare class Negentropy {
55
+ readonly items: Item[];
56
+ readonly isClient: boolean;
57
+ private readonly keys;
58
+ constructor(items: Iterable<Item>, isClient?: boolean);
59
+ /** Index of the first item not below the bound. */
60
+ private bisect;
61
+ private range;
62
+ private fp;
63
+ /** Ranges covering [lower, upper): an id list when small, else sixteen
64
+ * fingerprinted buckets with the remainder spread over the first. An empty
65
+ * range is still answered. */
66
+ private split;
67
+ /** The client's opening message: the whole space, split. */
68
+ initiate(): Uint8Array;
69
+ /** Process one message: [reply or null, have, need]. have/need are only
70
+ * populated for the client; a null reply ends the protocol. */
71
+ reconcile(message: Uint8Array): [Uint8Array | null, string[], string[]];
72
+ }
73
+ export interface ReconcileReport {
74
+ have: string[];
75
+ need: string[];
76
+ rounds: number;
77
+ bytesSent: number;
78
+ bytesReceived: number;
79
+ }
80
+ /** Run a whole reconciliation in process and report what it cost. */
81
+ export declare function reconcile(clientItems: Iterable<Item>, serverItems: Iterable<Item>, maxRounds?: number): ReconcileReport;