@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.
- package/README.md +103 -2
- package/dist/constants.d.ts +27 -0
- package/dist/constants.js +32 -0
- package/dist/descriptor.d.ts +29 -0
- package/dist/descriptor.js +73 -0
- package/dist/did.d.ts +59 -0
- package/dist/did.js +221 -0
- package/dist/didcomm.d.ts +59 -0
- package/dist/didcomm.js +176 -0
- package/dist/encoding.d.ts +14 -0
- package/dist/encoding.js +68 -0
- package/dist/event.d.ts +22 -0
- package/dist/event.js +42 -0
- package/dist/giftwrap.d.ts +29 -0
- package/dist/giftwrap.js +100 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +20 -0
- package/dist/keys.d.ts +6 -0
- package/dist/keys.js +31 -0
- package/dist/mediation/leaf.d.ts +121 -0
- package/dist/mediation/leaf.js +238 -0
- package/dist/mediation/messages.d.ts +96 -0
- package/dist/mediation/messages.js +79 -0
- package/dist/negentropy.d.ts +81 -0
- package/dist/negentropy.js +352 -0
- package/dist/nip44.d.ts +18 -0
- package/dist/nip44.js +119 -0
- package/dist/pwa/browser-leaf.d.ts +15 -0
- package/dist/pwa/browser-leaf.js +91 -0
- package/dist/pwa/hub.d.ts +51 -0
- package/dist/pwa/hub.js +137 -0
- package/dist/pwa/store.d.ts +39 -0
- package/dist/pwa/store.js +157 -0
- package/dist/relay.d.ts +67 -0
- package/dist/relay.js +232 -0
- package/dist/seal.d.ts +56 -0
- package/dist/seal.js +146 -0
- package/dist/session.d.ts +75 -0
- package/dist/session.js +230 -0
- package/package.json +45 -4
- package/src/constants.ts +36 -0
- package/src/descriptor.ts +88 -0
- package/src/did.ts +222 -0
- package/src/didcomm.ts +196 -0
- package/src/encoding.ts +67 -0
- package/src/event.ts +56 -0
- package/src/giftwrap.ts +108 -0
- package/src/index.ts +20 -0
- package/src/keys.ts +33 -0
- package/src/mediation/leaf.ts +292 -0
- package/src/mediation/messages.ts +124 -0
- package/src/negentropy.ts +357 -0
- package/src/nip44.ts +110 -0
- package/src/pwa/browser-leaf.ts +99 -0
- package/src/pwa/hub.ts +173 -0
- package/src/pwa/store.ts +173 -0
- package/src/relay.ts +273 -0
- package/src/seal.ts +154 -0
- package/src/session.ts +255 -0
package/src/keys.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The three keys a node holds, and their Multikey encodings (core
|
|
2
|
+
// fleetmesh_core/crypto/keys.py):
|
|
3
|
+
//
|
|
4
|
+
// node secp256k1, x-only; the nostr identity and the did:nostr subject.
|
|
5
|
+
// agreement X25519; every DIDComm v2 envelope.
|
|
6
|
+
// transport Ed25519; iroh NodeId, libp2p PeerId. A leaf has no use for it
|
|
7
|
+
// but must still read it off a descriptor.
|
|
8
|
+
//
|
|
9
|
+
// A descriptor Multikey is multibase 'f' (lowercase hex) over the multicodec
|
|
10
|
+
// varint and the key: fe70102<x> (compressed, even y), fec01<x25519>,
|
|
11
|
+
// fed01<ed25519>.
|
|
12
|
+
import { hexToBytes } from './encoding.ts';
|
|
13
|
+
|
|
14
|
+
export type KeyKind = 'node' | 'agreement' | 'transport';
|
|
15
|
+
export const KEY_KINDS: readonly KeyKind[] = ['node', 'agreement', 'transport'];
|
|
16
|
+
|
|
17
|
+
export const PREFIX: Record<KeyKind, string> = { node: 'fe70102', agreement: 'fec01', transport: 'fed01' };
|
|
18
|
+
|
|
19
|
+
export function multikey(kind: KeyKind, raw: Uint8Array): string {
|
|
20
|
+
if (!KEY_KINDS.includes(kind) || raw.length !== 32) throw new Error('a Multikey here is node, agreement or transport over 32 bytes');
|
|
21
|
+
let hex = '';
|
|
22
|
+
for (const b of raw) hex += b.toString(16).padStart(2, '0');
|
|
23
|
+
return PREFIX[kind] + hex;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** [kind, raw 32 bytes]. Rejects anything that is not one of the three. */
|
|
27
|
+
export function parseMultikey(s: string): [KeyKind, Uint8Array] {
|
|
28
|
+
for (const kind of KEY_KINDS) {
|
|
29
|
+
const p = PREFIX[kind];
|
|
30
|
+
if (s.startsWith(p) && s.length === p.length + 64) return [kind, hexToBytes(s.slice(p.length))];
|
|
31
|
+
}
|
|
32
|
+
throw new Error('not a fleetmesh Multikey: ' + JSON.stringify(s.slice(0, 12)));
|
|
33
|
+
}
|
|
@@ -0,0 +1,292 @@
|
|
|
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.ts';
|
|
16
|
+
import { bytesToHex } from '../encoding.ts';
|
|
17
|
+
import { type NostrEvent, verifyEvent } from '../event.ts';
|
|
18
|
+
import {
|
|
19
|
+
type Attachment, type DeliveredMessage, type ForwardBody, type KeylistUpdate, type KeylistUpdateBody, type KeylistUpdateResponseBody, KEYLIST_UPDATE_RESPONSE,
|
|
20
|
+
makeForward, makeKeylistUpdate, makeMediateRequest, makePickupDeliveryRequest, makePickupMessagesReceived,
|
|
21
|
+
MEDIATE_DENY, MEDIATE_GRANT, type MediateDenyBody, type MediateGrantBody, type Message, PICKUP_DELIVERY,
|
|
22
|
+
PICKUP_LIMIT_DEFAULT, type PickupDeliveryBody, type PickupDeliveryRequestBody, type PickupMessagesReceivedBody,
|
|
23
|
+
} from './messages.ts';
|
|
24
|
+
|
|
25
|
+
/** NIP-66 / kind 11801 query a leaf with no peers sends to bootstrap relays. */
|
|
26
|
+
export const DESCRIPTOR_KIND = 11801;
|
|
27
|
+
export const COLD_START_FILTER = { kinds: [DESCRIPTOR_KIND], '#c': ['mediator'] } as const;
|
|
28
|
+
|
|
29
|
+
export class MediationError extends Error {}
|
|
30
|
+
|
|
31
|
+
export interface MediationGrantInfo { routing_keys: string[]; endpoint: string | null; granted_at: number }
|
|
32
|
+
|
|
33
|
+
export interface MediatorCandidate {
|
|
34
|
+
descriptor: NostrEvent;
|
|
35
|
+
/** did:nostr of the anchor: the DID the leaf addresses mediation to. */
|
|
36
|
+
did: string;
|
|
37
|
+
/** The preferred wss:// endpoint (lowest priority number). */
|
|
38
|
+
endpoint: string;
|
|
39
|
+
/** The operator the descriptor names, or the anchor's own key when it names none. */
|
|
40
|
+
operator: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface DiscoverOptions {
|
|
44
|
+
requiredCount?: number;
|
|
45
|
+
requireDistinctOperators?: boolean;
|
|
46
|
+
/** Refuse descriptors whose signature does not verify. Default true: a
|
|
47
|
+
* leaf reads these off public relays, where anyone can publish one naming
|
|
48
|
+
* a real anchor's key beside their own endpoint. */
|
|
49
|
+
verify?: boolean;
|
|
50
|
+
/** Unix seconds; when given, descriptors past their `expiration` are refused. */
|
|
51
|
+
now?: number;
|
|
52
|
+
/** Accept ws:// as well as wss://. For local development only: a page
|
|
53
|
+
* served over https cannot open ws://, and nothing on it is private. */
|
|
54
|
+
allowInsecure?: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const first = (tags: string[][], name: string) => tags.find((t) => t[0] === name)?.[1];
|
|
58
|
+
|
|
59
|
+
/** Select independent mediator anchors from kind 11801 descriptors, in the
|
|
60
|
+
* order given (the Three-Layer Operator Independence Model): each carries
|
|
61
|
+
* ['c', 'mediator'] and a WebSocket endpoint, and, by default, no two share
|
|
62
|
+
* an operator. */
|
|
63
|
+
export function discoverMediators(descriptors: Iterable<NostrEvent>, opts: DiscoverOptions = {}): MediatorCandidate[] {
|
|
64
|
+
const { requiredCount = 2, requireDistinctOperators = true, verify = true, now, allowInsecure = false } = opts;
|
|
65
|
+
const schemes = allowInsecure ? ['wss', 'ws'] : ['wss'];
|
|
66
|
+
const selected: MediatorCandidate[] = [];
|
|
67
|
+
const operators = new Set<string>(), anchors = new Set<string>();
|
|
68
|
+
for (const ev of descriptors) {
|
|
69
|
+
if (selected.length >= requiredCount) break;
|
|
70
|
+
if (!ev || ev.kind !== DESCRIPTOR_KIND || !Array.isArray(ev.tags)) continue;
|
|
71
|
+
if (!ev.tags.some((t) => t[0] === 'c' && t[1] === 'mediator')) continue;
|
|
72
|
+
const eps = ev.tags.filter((t) => t[0] === 'endpoint' && schemes.includes(t[1]!) && typeof t[2] === 'string')
|
|
73
|
+
.sort((a, b) => (a.length > 3 ? +a[3]! : 50) - (b.length > 3 ? +b[3]! : 50));
|
|
74
|
+
if (!eps.length) continue;
|
|
75
|
+
if (verify && !verifyEvent(ev)) continue;
|
|
76
|
+
const exp = first(ev.tags, 'expiration');
|
|
77
|
+
if (now !== undefined && exp !== undefined && /^\d+$/.test(exp) && now >= +exp) continue;
|
|
78
|
+
if (anchors.has(ev.pubkey)) continue;
|
|
79
|
+
const operator = first(ev.tags, 'operator') || ev.pubkey;
|
|
80
|
+
if (requireDistinctOperators && operators.has(operator)) continue;
|
|
81
|
+
operators.add(operator);
|
|
82
|
+
anchors.add(ev.pubkey);
|
|
83
|
+
selected.push({ descriptor: ev, did: 'did:nostr:' + ev.pubkey, endpoint: eps[0]![2]!, operator });
|
|
84
|
+
}
|
|
85
|
+
return selected;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The two secrets a leaf holds: its node key (secp256k1, the did:nostr
|
|
89
|
+
* subject; signs its events and seals its wraps) and its agreement key
|
|
90
|
+
* (X25519, opens every envelope addressed to #agree). */
|
|
91
|
+
export interface LeafKeys { nodePk: string; agreementSk: Uint8Array }
|
|
92
|
+
|
|
93
|
+
export interface OpenedEnvelope { attachment: string; message: unknown; skid: string | null }
|
|
94
|
+
export interface OpenedDelivery {
|
|
95
|
+
id: string;
|
|
96
|
+
sender: string;
|
|
97
|
+
recipient_key: string;
|
|
98
|
+
enqueued_at: number;
|
|
99
|
+
envelopes: OpenedEnvelope[];
|
|
100
|
+
/** Attachments that would not open, with why. The message is still acked:
|
|
101
|
+
* an envelope that does not open now never will, and leaving it in the
|
|
102
|
+
* inbox only makes every later drain return it again. */
|
|
103
|
+
errors: { attachment: string; error: string }[];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
type Pending = { kind: 'mediate' | 'keylist' | 'pickup'; mediator: string; updates?: KeylistUpdate[] };
|
|
107
|
+
|
|
108
|
+
/** What a leaf must remember between launches: plain JSON, no secrets. */
|
|
109
|
+
export interface LeafClientState {
|
|
110
|
+
mediators: [string, MediationGrantInfo][];
|
|
111
|
+
denied: [string, string][];
|
|
112
|
+
keylists: [string, string[]][];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** One leaf's mediation state across its mediators. */
|
|
116
|
+
export class LeafClient {
|
|
117
|
+
readonly did: string;
|
|
118
|
+
readonly kid: string;
|
|
119
|
+
readonly mediators = new Map<string, MediationGrantInfo>();
|
|
120
|
+
readonly denied = new Map<string, string>();
|
|
121
|
+
/** Recipient keys registered with each mediator. The anchor registers the
|
|
122
|
+
* leaf's own DID on admission; keylist updates add and remove the rest. */
|
|
123
|
+
readonly keylists = new Map<string, Set<string>>();
|
|
124
|
+
private readonly keys: LeafKeys;
|
|
125
|
+
private readonly pending = new Map<string, Pending>();
|
|
126
|
+
private readonly clock: () => number;
|
|
127
|
+
|
|
128
|
+
constructor(keys: LeafKeys, clock: () => number = () => Math.floor(Date.now() / 1000)) {
|
|
129
|
+
this.keys = keys;
|
|
130
|
+
this.did = 'did:nostr:' + keys.nodePk;
|
|
131
|
+
this.kid = this.did + '#agree';
|
|
132
|
+
this.clock = clock;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private track<T extends Message<any>>(msg: T, p: Pending): T {
|
|
136
|
+
this.pending.set(msg.id, p);
|
|
137
|
+
return msg;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The pending request a response answers: by thid, from the mediator it was sent to. */
|
|
141
|
+
private answering(msg: Message<any>, kinds: Pending['kind'][]): Pending {
|
|
142
|
+
const p = this.pending.get(msg.thid);
|
|
143
|
+
if (!p || !kinds.includes(p.kind)) throw new MediationError(`unsolicited ${msg.type.split('/').pop()} (thid ${msg.thid})`);
|
|
144
|
+
if (msg.from !== p.mediator) throw new MediationError(`answer to ${msg.thid} came from ${msg.from}, not ${p.mediator}`);
|
|
145
|
+
if (!Array.isArray(msg.to) || !msg.to.includes(this.did)) throw new MediationError('answer is not addressed to this leaf');
|
|
146
|
+
this.pending.delete(msg.thid);
|
|
147
|
+
return p;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
isGranted = (mediatorDid: string): boolean => this.mediators.has(mediatorDid);
|
|
151
|
+
|
|
152
|
+
/** Grants, denials and keylists, for storage. Pending requests are not
|
|
153
|
+
* kept: an answer to a request from a previous launch is unsolicited. */
|
|
154
|
+
snapshot(): LeafClientState {
|
|
155
|
+
return {
|
|
156
|
+
mediators: [...this.mediators].map(([k, v]) => [k, { ...v, routing_keys: [...v.routing_keys] }]),
|
|
157
|
+
denied: [...this.denied],
|
|
158
|
+
keylists: [...this.keylists].map(([k, v]) => [k, [...v]]),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Replace this client's state with a snapshot. */
|
|
163
|
+
restore(state: LeafClientState): void {
|
|
164
|
+
this.mediators.clear();
|
|
165
|
+
this.denied.clear();
|
|
166
|
+
this.keylists.clear();
|
|
167
|
+
for (const [k, v] of state.mediators ?? []) this.mediators.set(k, { ...v, routing_keys: [...v.routing_keys] });
|
|
168
|
+
for (const [k, v] of state.denied ?? []) this.denied.set(k, v);
|
|
169
|
+
for (const [k, v] of state.keylists ?? []) this.keylists.set(k, new Set(v));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ---- admission --------------------------------------------------------
|
|
173
|
+
buildMediateRequest(mediatorDid: string): Message<Record<string, never>> {
|
|
174
|
+
return this.track(makeMediateRequest(this.did, mediatorDid), { kind: 'mediate', mediator: mediatorDid });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** A mediate-grant or mediate-deny answering one of this leaf's requests. */
|
|
178
|
+
recordMediationResponse(msg: Message<MediateGrantBody | MediateDenyBody>): 'granted' | 'denied' {
|
|
179
|
+
if (msg.type !== MEDIATE_GRANT && msg.type !== MEDIATE_DENY) throw new MediationError('not a mediation response: ' + msg.type);
|
|
180
|
+
const { mediator } = this.answering(msg, ['mediate']);
|
|
181
|
+
if (msg.type === MEDIATE_DENY) {
|
|
182
|
+
this.denied.set(mediator, String((msg.body as MediateDenyBody).reason ?? ''));
|
|
183
|
+
return 'denied';
|
|
184
|
+
}
|
|
185
|
+
const body = msg.body as MediateGrantBody;
|
|
186
|
+
if (!Array.isArray(body.routing_keys) || !body.routing_keys.every((k) => typeof k === 'string'))
|
|
187
|
+
throw new MediationError('a grant carries routing_keys');
|
|
188
|
+
this.mediators.set(mediator, {
|
|
189
|
+
routing_keys: [...body.routing_keys],
|
|
190
|
+
endpoint: typeof body.endpoint === 'string' ? body.endpoint : null,
|
|
191
|
+
granted_at: this.clock(),
|
|
192
|
+
});
|
|
193
|
+
this.denied.delete(mediator);
|
|
194
|
+
this.keylists.set(mediator, new Set([this.did]));
|
|
195
|
+
return 'granted';
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ---- keylist ----------------------------------------------------------
|
|
199
|
+
buildKeylistUpdate(mediatorDid: string, add: string[] = [], remove: string[] = []): Message<KeylistUpdateBody> {
|
|
200
|
+
this.requireGrant(mediatorDid);
|
|
201
|
+
const updates: KeylistUpdate[] = [
|
|
202
|
+
...add.map((k): KeylistUpdate => ({ recipient_key: k, action: 'add' })),
|
|
203
|
+
...remove.map((k): KeylistUpdate => ({ recipient_key: k, action: 'remove' })),
|
|
204
|
+
];
|
|
205
|
+
if (!updates.length) throw new MediationError('a keylist update needs at least one key');
|
|
206
|
+
return this.track(makeKeylistUpdate(this.did, mediatorDid, updates), { kind: 'keylist', mediator: mediatorDid, updates });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Apply what the mediator says it did; a key it did not mention is unchanged. */
|
|
210
|
+
recordKeylistUpdateResponse(msg: Message<KeylistUpdateResponseBody>): KeylistUpdateResponseBody['updated'] {
|
|
211
|
+
if (msg.type !== KEYLIST_UPDATE_RESPONSE) throw new MediationError('not a keylist-update-response: ' + msg.type);
|
|
212
|
+
const { mediator, updates = [] } = this.answering(msg, ['keylist']);
|
|
213
|
+
const asked = new Set(updates.map((u) => u.action + ' ' + u.recipient_key));
|
|
214
|
+
const keys = this.keylists.get(mediator) ?? new Set<string>();
|
|
215
|
+
const updated = Array.isArray(msg.body?.updated) ? msg.body.updated : [];
|
|
216
|
+
for (const u of updated) {
|
|
217
|
+
// A result for a key this leaf never asked about changes nothing.
|
|
218
|
+
if (!asked.has(u.action + ' ' + u.recipient_key)) continue;
|
|
219
|
+
if (u.action === 'add' && u.result === 'success') keys.add(u.recipient_key);
|
|
220
|
+
if (u.action === 'remove' && (u.result === 'success' || u.result === 'no_change')) keys.delete(u.recipient_key);
|
|
221
|
+
}
|
|
222
|
+
this.keylists.set(mediator, keys);
|
|
223
|
+
return updated;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// ---- pickup -----------------------------------------------------------
|
|
227
|
+
buildDeliveryRequest(mediatorDid: string, limit = PICKUP_LIMIT_DEFAULT, recipientKey?: string): Message<PickupDeliveryRequestBody> {
|
|
228
|
+
this.requireGrant(mediatorDid);
|
|
229
|
+
return this.track(makePickupDeliveryRequest(this.did, mediatorDid, limit, recipientKey), { kind: 'pickup', mediator: mediatorDid });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** One delivery-request per recipient key registered with this mediator.
|
|
233
|
+
* meshnode's MediatorService narrows an unnamed drain to the leaf's own DID
|
|
234
|
+
* (its default target is always in the keylist), so mail sent to any other
|
|
235
|
+
* registered key only comes out when that key is named. Asking per key
|
|
236
|
+
* drains everything from that anchor, and from one that reads an unnamed
|
|
237
|
+
* drain as all keys. */
|
|
238
|
+
buildDeliveryRequests(mediatorDid: string, limit = PICKUP_LIMIT_DEFAULT): Message<PickupDeliveryRequestBody>[] {
|
|
239
|
+
this.requireGrant(mediatorDid);
|
|
240
|
+
const keys = [...(this.keylists.get(mediatorDid) ?? [this.did])];
|
|
241
|
+
return keys.map((k) => this.buildDeliveryRequest(mediatorDid, limit, k === this.did ? undefined : k));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Open a delivery: every attachment's inner JWE, addressed to this leaf's
|
|
245
|
+
* #agree key. resolveSender maps an authcrypt skid to that sender's X25519
|
|
246
|
+
* key; without it only anoncrypt envelopes open. */
|
|
247
|
+
openDelivery(msg: Message<PickupDeliveryBody>, resolveSender?: (skid: string) => Uint8Array | null | undefined): OpenedDelivery[] {
|
|
248
|
+
if (msg.type !== PICKUP_DELIVERY) throw new MediationError('not a pickup delivery: ' + msg.type);
|
|
249
|
+
this.answering(msg, ['pickup']);
|
|
250
|
+
const rows: DeliveredMessage[] = Array.isArray(msg.body?.messages) ? msg.body.messages : [];
|
|
251
|
+
return rows.filter((r) => r && typeof r.id === 'string').map((r) => {
|
|
252
|
+
const out: OpenedDelivery = { id: r.id, sender: r.sender ?? '', recipient_key: r.recipient_key ?? '', enqueued_at: r.enqueued_at ?? 0, envelopes: [], errors: [] };
|
|
253
|
+
for (const att of Array.isArray(r.attachments) ? r.attachments : []) {
|
|
254
|
+
const name = typeof att?.id === 'string' ? att.id : '';
|
|
255
|
+
try {
|
|
256
|
+
const jwe = att?.data?.json as didcomm.JWE | undefined;
|
|
257
|
+
if (!jwe || typeof jwe !== 'object') throw new MediationError('attachment carries no JSON envelope');
|
|
258
|
+
const [message, skid] = didcomm.decrypt(jwe, this.kid, this.keys.agreementSk, resolveSender);
|
|
259
|
+
const from = message && typeof message === 'object' ? (message as { from?: unknown }).from : undefined;
|
|
260
|
+
if (typeof from === 'string') {
|
|
261
|
+
if (skid === null || from !== skid.split('#')[0]) {
|
|
262
|
+
throw new MediationError('inner message.from does not match authenticated skid');
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
out.envelopes.push({ attachment: name, message, skid });
|
|
266
|
+
} catch (e) {
|
|
267
|
+
out.errors.push({ attachment: name, error: (e as Error).message });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return out;
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** messages-received for a drained batch, so the mediator purges it. */
|
|
275
|
+
buildMessagesReceived(mediatorDid: string, ids: string[]): Message<PickupMessagesReceivedBody> {
|
|
276
|
+
this.requireGrant(mediatorDid);
|
|
277
|
+
return makePickupMessagesReceived(this.did, mediatorDid, ids);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// ---- sending through another leaf's mediator --------------------------
|
|
281
|
+
/** Wrap an inner encrypted envelope in a routing/2.0 forward to the
|
|
282
|
+
* recipient leaf's mediator. */
|
|
283
|
+
wrapForward(innerEnvelope: string | object, mediatorDid: string, recipientLeafDid: string): Message<ForwardBody> {
|
|
284
|
+
const json = typeof innerEnvelope === 'string' ? JSON.parse(innerEnvelope) : innerEnvelope;
|
|
285
|
+
const attachment: Attachment = { id: 'att-' + bytesToHex(randomBytes(8)), data: { json } };
|
|
286
|
+
return makeForward(this.did, mediatorDid, recipientLeafDid, [attachment]);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private requireGrant(mediatorDid: string): void {
|
|
290
|
+
if (!this.mediators.has(mediatorDid)) throw new MediationError('no mediation grant from ' + mediatorDid);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
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.ts';
|
|
7
|
+
|
|
8
|
+
export const MEDIATE_REQUEST = 'https://didcomm.org/coordinate-mediation/2.0/mediate-request';
|
|
9
|
+
export const MEDIATE_GRANT = 'https://didcomm.org/coordinate-mediation/2.0/mediate-grant';
|
|
10
|
+
export const MEDIATE_DENY = 'https://didcomm.org/coordinate-mediation/2.0/mediate-deny';
|
|
11
|
+
export const KEYLIST_UPDATE = 'https://didcomm.org/coordinate-mediation/2.0/keylist-update';
|
|
12
|
+
export const KEYLIST_UPDATE_RESPONSE = 'https://didcomm.org/coordinate-mediation/2.0/keylist-update-response';
|
|
13
|
+
export const KEYLIST_QUERY = 'https://didcomm.org/coordinate-mediation/2.0/keylist-query';
|
|
14
|
+
export const KEYLIST_RESPONSE = 'https://didcomm.org/coordinate-mediation/2.0/keylist-response';
|
|
15
|
+
export const ROUTING_FORWARD = 'https://didcomm.org/routing/2.0/forward';
|
|
16
|
+
export const PICKUP_STATUS_REQUEST = 'https://didcomm.org/messagepickup/2.0/status-request';
|
|
17
|
+
export const PICKUP_STATUS = 'https://didcomm.org/messagepickup/2.0/status';
|
|
18
|
+
export const PICKUP_DELIVERY_REQUEST = 'https://didcomm.org/messagepickup/2.0/delivery-request';
|
|
19
|
+
export const PICKUP_DELIVERY = 'https://didcomm.org/messagepickup/2.0/delivery';
|
|
20
|
+
export const PICKUP_MESSAGES_RECEIVED = 'https://didcomm.org/messagepickup/2.0/messages-received';
|
|
21
|
+
|
|
22
|
+
export const PIURIS = [
|
|
23
|
+
'https://didcomm.org/coordinate-mediation/2.0',
|
|
24
|
+
'https://didcomm.org/routing/2.0',
|
|
25
|
+
'https://didcomm.org/messagepickup/2.0',
|
|
26
|
+
] as const;
|
|
27
|
+
|
|
28
|
+
// One drain per delivery-request, between one message and this many. The
|
|
29
|
+
// anchor clamps whatever it is sent; the leaf asks within bounds.
|
|
30
|
+
export const PICKUP_LIMIT_MIN = 1;
|
|
31
|
+
export const PICKUP_LIMIT_MAX = 100;
|
|
32
|
+
export const PICKUP_LIMIT_DEFAULT = 10;
|
|
33
|
+
|
|
34
|
+
/** `limit` as an int in [MIN, MAX], the way the anchor reads it. */
|
|
35
|
+
export function clampPickupLimit(raw: unknown): number {
|
|
36
|
+
const n = typeof raw === 'number' && Number.isFinite(raw) ? Math.trunc(raw)
|
|
37
|
+
: typeof raw === 'string' && /^\s*[+-]?\d+\s*$/.test(raw) ? parseInt(raw, 10) : PICKUP_LIMIT_DEFAULT;
|
|
38
|
+
return Math.max(PICKUP_LIMIT_MIN, Math.min(PICKUP_LIMIT_MAX, n));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface Message<B = Record<string, unknown>> {
|
|
42
|
+
id: string;
|
|
43
|
+
type: string;
|
|
44
|
+
from: string;
|
|
45
|
+
to: string[];
|
|
46
|
+
thid: string;
|
|
47
|
+
body: B;
|
|
48
|
+
attachments?: Attachment[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface Attachment { id: string; data: { json: unknown } }
|
|
52
|
+
|
|
53
|
+
export interface MediateGrantBody { routing_keys: string[]; endpoint?: string }
|
|
54
|
+
export interface MediateDenyBody { reason: string }
|
|
55
|
+
export type KeylistAction = 'add' | 'remove';
|
|
56
|
+
export interface KeylistUpdate { recipient_key: string; action: KeylistAction }
|
|
57
|
+
export interface KeylistUpdated extends KeylistUpdate { result: string }
|
|
58
|
+
export interface KeylistUpdateBody { updates: KeylistUpdate[] }
|
|
59
|
+
export interface KeylistUpdateResponseBody { updated: KeylistUpdated[] }
|
|
60
|
+
export interface ForwardBody { next: string }
|
|
61
|
+
export interface PickupStatusRequestBody { recipient_key?: string }
|
|
62
|
+
export interface PickupStatusBody { message_count: number; recipient_key?: string }
|
|
63
|
+
export interface PickupDeliveryRequestBody { limit: number; recipient_key?: string }
|
|
64
|
+
/** What the anchor puts in a delivery: one row of its inbox. */
|
|
65
|
+
export interface DeliveredMessage { id: string; recipient_key: string; sender: string; attachments: Attachment[]; enqueued_at: number }
|
|
66
|
+
export interface PickupDeliveryBody { messages: DeliveredMessage[]; recipient_key?: string }
|
|
67
|
+
export interface PickupMessagesReceivedBody { message_id_list: string[] }
|
|
68
|
+
|
|
69
|
+
const newId = (prefix: string) => prefix + bytesToHex(randomBytes(8));
|
|
70
|
+
|
|
71
|
+
function make<B>(prefix: string, type: string, from: string, to: string, body: B, thid?: string): Message<B> {
|
|
72
|
+
const id = newId(prefix);
|
|
73
|
+
return { id, type, from, to: [to], thid: thid ?? id, body };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export const makeMediateRequest = (from: string, to: string, thid?: string) =>
|
|
77
|
+
make<Record<string, never>>('med-req-', MEDIATE_REQUEST, from, to, {}, thid);
|
|
78
|
+
|
|
79
|
+
export function makeMediateGrant(from: string, to: string, routingKeys: string[], endpoint?: string, thid?: string) {
|
|
80
|
+
const body: MediateGrantBody = { routing_keys: [...routingKeys] };
|
|
81
|
+
if (endpoint) body.endpoint = endpoint;
|
|
82
|
+
return make('med-grant-', MEDIATE_GRANT, from, to, body, thid);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export const makeMediateDeny = (from: string, to: string, reason = 'capacity', thid?: string) =>
|
|
86
|
+
make<MediateDenyBody>('med-deny-', MEDIATE_DENY, from, to, { reason }, thid);
|
|
87
|
+
|
|
88
|
+
export const makeKeylistUpdate = (from: string, to: string, updates: KeylistUpdate[], thid?: string) =>
|
|
89
|
+
make<KeylistUpdateBody>('kl-upd-', KEYLIST_UPDATE, from, to, { updates: [...updates] }, thid);
|
|
90
|
+
|
|
91
|
+
export const makeKeylistUpdateResponse = (from: string, to: string, updated: KeylistUpdated[], thid?: string) =>
|
|
92
|
+
make<KeylistUpdateResponseBody>('kl-resp-', KEYLIST_UPDATE_RESPONSE, from, to, { updated: [...updated] }, thid);
|
|
93
|
+
|
|
94
|
+
/** routing/2.0 forward wrapping inner encrypted envelopes as attachments. */
|
|
95
|
+
export function makeForward(from: string, to: string, next: string, attachments: Attachment[], thid?: string): Message<ForwardBody> {
|
|
96
|
+
return { ...make<ForwardBody>('fwd-', ROUTING_FORWARD, from, to, { next }, thid), attachments: [...attachments] };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function makePickupStatusRequest(from: string, to: string, recipientKey?: string, thid?: string) {
|
|
100
|
+
const body: PickupStatusRequestBody = {};
|
|
101
|
+
if (recipientKey) body.recipient_key = recipientKey;
|
|
102
|
+
return make('pck-req-', PICKUP_STATUS_REQUEST, from, to, body, thid);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function makePickupStatus(from: string, to: string, messageCount = 0, recipientKey?: string, thid?: string) {
|
|
106
|
+
const body: PickupStatusBody = { message_count: messageCount };
|
|
107
|
+
if (recipientKey) body.recipient_key = recipientKey;
|
|
108
|
+
return make('pck-stat-', PICKUP_STATUS, from, to, body, thid);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function makePickupDeliveryRequest(from: string, to: string, limit = PICKUP_LIMIT_DEFAULT, recipientKey?: string, thid?: string) {
|
|
112
|
+
const body: PickupDeliveryRequestBody = { limit };
|
|
113
|
+
if (recipientKey) body.recipient_key = recipientKey;
|
|
114
|
+
return make('pck-del-req-', PICKUP_DELIVERY_REQUEST, from, to, body, thid);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function makePickupDelivery(from: string, to: string, messages: DeliveredMessage[], recipientKey?: string, thid?: string) {
|
|
118
|
+
const body: PickupDeliveryBody = { messages: [...messages] };
|
|
119
|
+
if (recipientKey) body.recipient_key = recipientKey;
|
|
120
|
+
return make('pck-del-', PICKUP_DELIVERY, from, to, body, thid);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export const makePickupMessagesReceived = (from: string, to: string, ids: string[], thid?: string) =>
|
|
124
|
+
make<PickupMessagesReceivedBody>('pck-ack-', PICKUP_MESSAGES_RECEIVED, from, to, { message_id_list: [...ids] }, thid);
|