@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/dist/seal.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// What a DIDComm message becomes on a relay, both ways, by the rules
|
|
2
|
+
// meshnode's relay rung keeps (node/transport/relay_rung/{wire,outbound,
|
|
3
|
+
// inbound}.py and node/transport/didcomm_inbound.py):
|
|
4
|
+
//
|
|
5
|
+
// out message -> authcrypt JWE to the peer's #agree key -> fragments when
|
|
6
|
+
// the JWE is over FRAGMENT_BYTES -> each a NIP-59 gift wrap to the
|
|
7
|
+
// peer's node key, kind 21059 (live) or 1059 (stored).
|
|
8
|
+
// in wrap -> unwrap (the seal signer is the sender) -> reassemble ->
|
|
9
|
+
// decrypt with this leaf's #agree key -> the three names must agree:
|
|
10
|
+
// the plaintext `from`, the authcrypt skid, and the seal signer.
|
|
11
|
+
//
|
|
12
|
+
// Anoncrypt opens too, unauthenticated: it is what first contact is, and the
|
|
13
|
+
// caller decides whether an unproven sender is worth reading.
|
|
14
|
+
import { randomBytes } from '@noble/curves/utils.js';
|
|
15
|
+
import * as didcomm from './didcomm.js';
|
|
16
|
+
import { bytesToHex, canonicalJson, isHex } from './encoding.js';
|
|
17
|
+
import { unwrap, WRAP_LIVE, WRAP_STORED, wrap } from './giftwrap.js';
|
|
18
|
+
export const FRAGMENT_BYTES = 24000;
|
|
19
|
+
export const MAX_FRAGMENTS = 64;
|
|
20
|
+
export const ENVELOPE_MAX = FRAGMENT_BYTES * MAX_FRAGMENTS;
|
|
21
|
+
export const PARTIALS_PER_SENDER = 4;
|
|
22
|
+
export const PARTIALS_MAX = 64;
|
|
23
|
+
export const PARTIAL_TTL_SECONDS = 600;
|
|
24
|
+
export const EMPTY_TYPE = 'https://didcomm.org/empty/1.0/empty';
|
|
25
|
+
export class SealError extends Error {
|
|
26
|
+
}
|
|
27
|
+
/** The JWE itself when it fits a wrap, else its pieces under one fragment id. */
|
|
28
|
+
export function fragments(jwe) {
|
|
29
|
+
const text = canonicalJson(jwe);
|
|
30
|
+
if (text.length <= FRAGMENT_BYTES)
|
|
31
|
+
return [jwe];
|
|
32
|
+
if (text.length > ENVELOPE_MAX) {
|
|
33
|
+
throw new SealError(`an envelope of ${text.length} bytes needs ${Math.ceil(text.length / FRAGMENT_BYTES)} fragments and the receiver refuses more than ${MAX_FRAGMENTS}; send less in one message`);
|
|
34
|
+
}
|
|
35
|
+
const frag = bytesToHex(randomBytes(8));
|
|
36
|
+
const parts = [];
|
|
37
|
+
for (let i = 0; i < text.length; i += FRAGMENT_BYTES)
|
|
38
|
+
parts.push(text.slice(i, i + FRAGMENT_BYTES));
|
|
39
|
+
return parts.map((data, i) => ({ frag, i, n: parts.length, data }));
|
|
40
|
+
}
|
|
41
|
+
/** Address, encrypt and wrap one message to a peer: the wraps to publish, in order. */
|
|
42
|
+
export function seal(message, me, to, opts = {}) {
|
|
43
|
+
const now = opts.now ?? Math.floor(Date.now() / 1000);
|
|
44
|
+
const msg = { ...message };
|
|
45
|
+
msg.from ??= 'did:nostr:' + me.pubkey;
|
|
46
|
+
msg.to ??= ['did:nostr:' + to.pubkey];
|
|
47
|
+
msg.created_time ??= now;
|
|
48
|
+
if (opts.stored && typeof msg.id === 'string')
|
|
49
|
+
msg.please_ack = [''];
|
|
50
|
+
const jwe = didcomm.encrypt(msg, [['did:nostr:' + to.pubkey + '#agree', to.agreementPub]], {
|
|
51
|
+
sender: ['did:nostr:' + me.pubkey + '#agree', me.agreementSk],
|
|
52
|
+
});
|
|
53
|
+
const kind = opts.stored ? WRAP_STORED : WRAP_LIVE;
|
|
54
|
+
return fragments(jwe).map((p) => wrap(p, me.nodeSk, to.pubkey, now, { kind }));
|
|
55
|
+
}
|
|
56
|
+
const pubkeyOfDid = (name) => {
|
|
57
|
+
if (typeof name !== 'string' || !name.startsWith('did:nostr:'))
|
|
58
|
+
return null;
|
|
59
|
+
const pk = name.slice('did:nostr:'.length).split('#', 1)[0].toLowerCase();
|
|
60
|
+
return isHex(pk, 64) ? pk : null;
|
|
61
|
+
};
|
|
62
|
+
/** Collects fragments by (sender, fragment id), bounded as the anchor bounds them. */
|
|
63
|
+
export class Reassembler {
|
|
64
|
+
partials = new Map();
|
|
65
|
+
/** The whole JWE once every fragment has arrived; null while waiting. */
|
|
66
|
+
add(frag, sender, now) {
|
|
67
|
+
const { frag: fid, i, n, data } = frag;
|
|
68
|
+
if (!Number.isInteger(n) || !Number.isInteger(i) || !(n > 0 && n <= MAX_FRAGMENTS && i >= 0 && i < n))
|
|
69
|
+
throw new SealError('fragment out of range');
|
|
70
|
+
if (typeof fid !== 'string' || fid.length > 64 || typeof data !== 'string' || data.length > FRAGMENT_BYTES + 16)
|
|
71
|
+
throw new SealError('fragment out of range');
|
|
72
|
+
for (const [k, v] of this.partials)
|
|
73
|
+
if (now - v.at > PARTIAL_TTL_SECONDS)
|
|
74
|
+
this.partials.delete(k);
|
|
75
|
+
const key = sender + ' ' + fid;
|
|
76
|
+
let p = this.partials.get(key);
|
|
77
|
+
if (!p) {
|
|
78
|
+
const mine = [...this.partials.keys()].filter((k) => k.startsWith(sender + ' ')).length;
|
|
79
|
+
if (mine >= PARTIALS_PER_SENDER || this.partials.size >= PARTIALS_MAX)
|
|
80
|
+
throw new SealError('fragment: too many unfinished envelopes');
|
|
81
|
+
p = { n, parts: new Map(), at: now };
|
|
82
|
+
this.partials.set(key, p);
|
|
83
|
+
}
|
|
84
|
+
if (p.n !== n) {
|
|
85
|
+
this.partials.delete(key);
|
|
86
|
+
throw new SealError('fragment: count changed mid-envelope');
|
|
87
|
+
}
|
|
88
|
+
p.parts.set(i, data);
|
|
89
|
+
if (p.parts.size < n)
|
|
90
|
+
return null;
|
|
91
|
+
this.partials.delete(key);
|
|
92
|
+
try {
|
|
93
|
+
return JSON.parse(Array.from({ length: n }, (_, k) => p.parts.get(k)).join(''));
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
throw new SealError('reassembled fragments are not JSON');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** Open one wrap addressed to this leaf. Null while a fragmented envelope is
|
|
101
|
+
* incomplete; throws with the reason for anything refused.
|
|
102
|
+
* resolveAgreement maps a sender's node key to its X25519 key (from its
|
|
103
|
+
* descriptor); a sender it cannot resolve cannot be authenticated. */
|
|
104
|
+
export function open(wrapEvent, me, resolveAgreement, reassembler, now) {
|
|
105
|
+
let payload, sealPk;
|
|
106
|
+
try {
|
|
107
|
+
[payload, sealPk] = unwrap(wrapEvent, me.nodeSk, now);
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
throw new SealError('wrap: ' + e.message);
|
|
111
|
+
}
|
|
112
|
+
if (payload && typeof payload === 'object' && 'frag' in payload) {
|
|
113
|
+
const whole = reassembler.add(payload, sealPk, now ?? Math.floor(Date.now() / 1000));
|
|
114
|
+
if (whole === null)
|
|
115
|
+
return null;
|
|
116
|
+
payload = whole;
|
|
117
|
+
}
|
|
118
|
+
if (!payload || typeof payload !== 'object' || !('protected' in payload) || !('recipients' in payload)) {
|
|
119
|
+
const t = payload?.type;
|
|
120
|
+
throw new SealError(typeof t === 'string' ? 'another protocol: ' + t.slice(0, 80) : 'payload is not a JWE');
|
|
121
|
+
}
|
|
122
|
+
let message, skid;
|
|
123
|
+
try {
|
|
124
|
+
[message, skid] = didcomm.decrypt(payload, 'did:nostr:' + me.pubkey + '#agree', me.agreementSk, (kid) => kid.endsWith('#agree') ? resolveAgreement(pubkeyOfDid(kid) ?? '') : null);
|
|
125
|
+
}
|
|
126
|
+
catch (e) {
|
|
127
|
+
throw new SealError('envelope: ' + e.message);
|
|
128
|
+
}
|
|
129
|
+
if (!message || typeof message !== 'object' || typeof message.type !== 'string' || typeof message.id !== 'string')
|
|
130
|
+
throw new SealError('plaintext is not a DIDComm message');
|
|
131
|
+
const claimed = pubkeyOfDid(message.from);
|
|
132
|
+
if (claimed === null)
|
|
133
|
+
throw new SealError('from is not a did:nostr');
|
|
134
|
+
if (claimed !== sealPk)
|
|
135
|
+
throw new SealError(`from ${claimed.slice(0, 8)} does not match the seal signer ${sealPk.slice(0, 8)}`);
|
|
136
|
+
if (skid !== null) {
|
|
137
|
+
const signer = pubkeyOfDid(skid);
|
|
138
|
+
if (signer === null)
|
|
139
|
+
throw new SealError('skid is not a did:nostr');
|
|
140
|
+
if (signer !== sealPk)
|
|
141
|
+
throw new SealError('skid does not match the seal signer');
|
|
142
|
+
}
|
|
143
|
+
if (message.thid !== undefined && typeof message.thid !== 'string')
|
|
144
|
+
throw new SealError('thid is not a string');
|
|
145
|
+
return { message, sender: sealPk, authenticated: skid !== null, wrapId: wrapEvent.id };
|
|
146
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type NostrEvent } from './event.js;
|
|
2
|
+
import { LeafClient, type LeafClientState, type OpenedDelivery } from './mediation/leaf.js;
|
|
3
|
+
import { type SocketFactory } from './relay.js;
|
|
4
|
+
import { type Opened } from './seal.js;
|
|
5
|
+
export declare class SessionError extends Error {
|
|
6
|
+
}
|
|
7
|
+
export interface LeafSessionOptions {
|
|
8
|
+
/** The leaf's node key (secp256k1, hex) and agreement key (X25519, raw). */
|
|
9
|
+
nodeSk: string;
|
|
10
|
+
agreementSk: Uint8Array;
|
|
11
|
+
/** The mediator: its node key and the wss:// endpoint its relay face serves. */
|
|
12
|
+
mediator: {
|
|
13
|
+
pubkey: string;
|
|
14
|
+
endpoint: string;
|
|
15
|
+
descriptor?: NostrEvent;
|
|
16
|
+
};
|
|
17
|
+
socket?: SocketFactory;
|
|
18
|
+
clock?: () => number;
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
/** Fields for this leaf's own descriptor. */
|
|
21
|
+
operator?: string;
|
|
22
|
+
powBits?: number;
|
|
23
|
+
/** Grants and keylists from a previous launch (LeafClient.snapshot()). */
|
|
24
|
+
state?: LeafClientState;
|
|
25
|
+
/** Called with a fresh snapshot whenever a grant or keylist changes. */
|
|
26
|
+
onState?: (state: LeafClientState) => void;
|
|
27
|
+
/** Messages nobody was waiting for: unsolicited traffic from the mediator. */
|
|
28
|
+
onMessage?: (m: Opened) => void;
|
|
29
|
+
/** Wraps that did not open, with why. Nothing else reports them. */
|
|
30
|
+
onDrop?: (why: string, wrapId: string) => void;
|
|
31
|
+
}
|
|
32
|
+
export declare class LeafSession {
|
|
33
|
+
readonly pubkey: string;
|
|
34
|
+
readonly client: LeafClient;
|
|
35
|
+
readonly mediatorDid: string;
|
|
36
|
+
private readonly opts;
|
|
37
|
+
private readonly clock;
|
|
38
|
+
private relay;
|
|
39
|
+
private sub;
|
|
40
|
+
private mediatorAgreement;
|
|
41
|
+
private descriptor;
|
|
42
|
+
private readonly waiters;
|
|
43
|
+
private readonly seen;
|
|
44
|
+
private readonly reassembler;
|
|
45
|
+
constructor(opts: LeafSessionOptions);
|
|
46
|
+
private newRelay;
|
|
47
|
+
private get timeout();
|
|
48
|
+
get connected(): boolean;
|
|
49
|
+
/** The mediator's agreement key, from a descriptor it signed and that is live. */
|
|
50
|
+
private learnMediator;
|
|
51
|
+
private within;
|
|
52
|
+
/** Connect, learn the mediator, publish this leaf's descriptor, listen. */
|
|
53
|
+
start(): Promise<void>;
|
|
54
|
+
/** After the socket died: a fresh connection and subscription, and a new
|
|
55
|
+
* descriptor only if the old one is close to expiring. */
|
|
56
|
+
resume(): Promise<void>;
|
|
57
|
+
close(): void;
|
|
58
|
+
private publishDescriptor;
|
|
59
|
+
private listen;
|
|
60
|
+
private onWrap;
|
|
61
|
+
/** Seal and publish; throws if the relay took none of the wraps. */
|
|
62
|
+
private send;
|
|
63
|
+
/** Send a message and wait for the mediator's answer on its thread. */
|
|
64
|
+
private request;
|
|
65
|
+
requestMediation(): Promise<'granted' | 'denied'>;
|
|
66
|
+
updateKeylist(add?: string[], remove?: string[]): Promise<import("./mediation/messages.js).KeylistUpdated[]>;
|
|
67
|
+
/** Drain every registered key until the mediator has nothing left, acking
|
|
68
|
+
* each batch so it purges what was taken. maxRounds bounds a mediator that
|
|
69
|
+
* keeps returning the same batch. */
|
|
70
|
+
pickup(opts?: {
|
|
71
|
+
limit?: number;
|
|
72
|
+
maxRounds?: number;
|
|
73
|
+
resolveSender?: (skid: string) => Uint8Array | null | undefined;
|
|
74
|
+
}): Promise<OpenedDelivery[]>;
|
|
75
|
+
}
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// A leaf's session with its mediator: the one wss:// connection the leaf
|
|
2
|
+
// profile allows, and everything said over it.
|
|
3
|
+
//
|
|
4
|
+
// start() connect (answering AUTH), learn the mediator's
|
|
5
|
+
// agreement key from its descriptor, publish this
|
|
6
|
+
// leaf's descriptor so the anchor can authenticate it,
|
|
7
|
+
// and subscribe for wraps addressed to this leaf -
|
|
8
|
+
// before anything is sent, because replies are kind
|
|
9
|
+
// 21059 and a relay keeps none of them.
|
|
10
|
+
// requestMediation() mediate-request, answered by grant or deny.
|
|
11
|
+
// updateKeylist() keylist-update, answered by keylist-update-response.
|
|
12
|
+
// pickup() delivery-request per registered key, opened and
|
|
13
|
+
// acked, until the inbox is empty.
|
|
14
|
+
//
|
|
15
|
+
// A phone's socket dies on screen lock. Nothing here survives that except
|
|
16
|
+
// the grant and keylist; resume() reconnects and resubscribes, and the next
|
|
17
|
+
// pickup() catches up. Messages the anchor stored as kind 1059 are replayed
|
|
18
|
+
// by the relay inside the subscription's two-day window.
|
|
19
|
+
import { agreementOf, buildLeafDescriptor, KIND as DESCRIPTOR_KIND } from './descriptor.js';
|
|
20
|
+
import { agreementPublic } from './didcomm.js';
|
|
21
|
+
import { pubkeyOf, signEvent, verifyEvent } from './event.js';
|
|
22
|
+
import { TWO_DAYS, WRAP_LIVE, WRAP_STORED } from './giftwrap.js';
|
|
23
|
+
import { LeafClient } from './mediation/leaf.js';
|
|
24
|
+
import { PICKUP_LIMIT_DEFAULT } from './mediation/messages.js';
|
|
25
|
+
import { authEvent, RelayConnection } from './relay.js';
|
|
26
|
+
import { EMPTY_TYPE, open, Reassembler, seal } from './seal.js';
|
|
27
|
+
export class SessionError extends Error {
|
|
28
|
+
}
|
|
29
|
+
const SEEN_MAX = 4096;
|
|
30
|
+
export class LeafSession {
|
|
31
|
+
pubkey;
|
|
32
|
+
client;
|
|
33
|
+
mediatorDid;
|
|
34
|
+
opts;
|
|
35
|
+
clock;
|
|
36
|
+
relay;
|
|
37
|
+
sub = null;
|
|
38
|
+
mediatorAgreement = null;
|
|
39
|
+
descriptor = null;
|
|
40
|
+
waiters = new Map();
|
|
41
|
+
seen = new Set();
|
|
42
|
+
reassembler = new Reassembler();
|
|
43
|
+
constructor(opts) {
|
|
44
|
+
this.opts = opts;
|
|
45
|
+
this.clock = opts.clock ?? (() => Math.floor(Date.now() / 1000));
|
|
46
|
+
this.pubkey = pubkeyOf(opts.nodeSk);
|
|
47
|
+
this.mediatorDid = 'did:nostr:' + opts.mediator.pubkey;
|
|
48
|
+
this.client = new LeafClient({ nodePk: this.pubkey, agreementSk: opts.agreementSk }, this.clock);
|
|
49
|
+
if (opts.state)
|
|
50
|
+
this.client.restore(opts.state);
|
|
51
|
+
this.relay = this.newRelay();
|
|
52
|
+
}
|
|
53
|
+
newRelay() {
|
|
54
|
+
return new RelayConnection(this.opts.mediator.endpoint, {
|
|
55
|
+
...(this.opts.socket ? { socket: this.opts.socket } : {}),
|
|
56
|
+
timeoutMs: this.timeout,
|
|
57
|
+
signAuth: (challenge, url) => authEvent((at, k, t, c) => signEvent(this.opts.nodeSk, at, k, t, c), challenge, url, this.clock()),
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
get timeout() {
|
|
61
|
+
return this.opts.timeoutMs ?? 10000;
|
|
62
|
+
}
|
|
63
|
+
get connected() {
|
|
64
|
+
return this.relay.connected && this.sub !== null;
|
|
65
|
+
}
|
|
66
|
+
/** The mediator's agreement key, from a descriptor it signed and that is live. */
|
|
67
|
+
async learnMediator() {
|
|
68
|
+
const now = this.clock();
|
|
69
|
+
const live = (d) => d.kind === DESCRIPTOR_KIND && d.pubkey === this.opts.mediator.pubkey && verifyEvent(d)
|
|
70
|
+
&& !d.tags.some((t) => t[0] === 'expiration' && /^\d+$/.test(t[1] ?? '') && +t[1] <= now);
|
|
71
|
+
let desc = this.opts.mediator.descriptor && live(this.opts.mediator.descriptor) ? this.opts.mediator.descriptor : null;
|
|
72
|
+
if (!desc) {
|
|
73
|
+
const found = [];
|
|
74
|
+
const sub = this.relay.subscribe([{ kinds: [DESCRIPTOR_KIND], authors: [this.opts.mediator.pubkey] }], (ev) => found.push(ev));
|
|
75
|
+
await this.within(sub.eose, 'the mediator\'s descriptor');
|
|
76
|
+
sub.close();
|
|
77
|
+
desc = found.filter(live).sort((a, b) => b.created_at - a.created_at)[0] ?? null;
|
|
78
|
+
}
|
|
79
|
+
const agree = desc ? agreementOf(desc) : null;
|
|
80
|
+
if (!agree)
|
|
81
|
+
throw new SessionError('no live descriptor with an agreement key for the mediator ' + this.opts.mediator.pubkey.slice(0, 16));
|
|
82
|
+
return agree;
|
|
83
|
+
}
|
|
84
|
+
within(p, what) {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
const t = setTimeout(() => reject(new SessionError(`no answer for ${what} in ${this.timeout}ms`)), this.timeout);
|
|
87
|
+
p.then((v) => { clearTimeout(t); resolve(v); }, (e) => { clearTimeout(t); reject(e); });
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/** Connect, learn the mediator, publish this leaf's descriptor, listen. */
|
|
91
|
+
async start() {
|
|
92
|
+
await this.relay.connect();
|
|
93
|
+
this.mediatorAgreement ??= await this.learnMediator();
|
|
94
|
+
await this.publishDescriptor();
|
|
95
|
+
await this.listen();
|
|
96
|
+
}
|
|
97
|
+
/** After the socket died: a fresh connection and subscription, and a new
|
|
98
|
+
* descriptor only if the old one is close to expiring. */
|
|
99
|
+
async resume() {
|
|
100
|
+
this.sub = null;
|
|
101
|
+
this.relay.close();
|
|
102
|
+
this.relay = this.newRelay();
|
|
103
|
+
await this.relay.connect();
|
|
104
|
+
this.mediatorAgreement ??= await this.learnMediator();
|
|
105
|
+
const exp = Number(this.descriptor?.tags.find((t) => t[0] === 'expiration')?.[1] ?? 0);
|
|
106
|
+
if (exp - this.clock() < 3600)
|
|
107
|
+
await this.publishDescriptor();
|
|
108
|
+
await this.listen();
|
|
109
|
+
}
|
|
110
|
+
close() {
|
|
111
|
+
this.sub?.close();
|
|
112
|
+
this.sub = null;
|
|
113
|
+
this.relay.close();
|
|
114
|
+
}
|
|
115
|
+
async publishDescriptor() {
|
|
116
|
+
const d = buildLeafDescriptor(this.opts.nodeSk, {
|
|
117
|
+
agreementPub: agreementPublic(this.opts.agreementSk),
|
|
118
|
+
mediators: [this.mediatorDid],
|
|
119
|
+
now: this.clock(),
|
|
120
|
+
...(this.opts.operator ? { operator: this.opts.operator } : {}),
|
|
121
|
+
...(this.opts.powBits ? { powBits: this.opts.powBits } : {}),
|
|
122
|
+
});
|
|
123
|
+
const r = await this.relay.publish(d);
|
|
124
|
+
if (!r.ok)
|
|
125
|
+
throw new SessionError('the mediator\'s relay refused this leaf\'s descriptor: ' + r.message);
|
|
126
|
+
this.descriptor = d;
|
|
127
|
+
}
|
|
128
|
+
async listen() {
|
|
129
|
+
const filter = { kinds: [WRAP_LIVE, WRAP_STORED], '#p': [this.pubkey], since: this.clock() - TWO_DAYS };
|
|
130
|
+
const sub = this.relay.subscribe([filter], (ev) => this.onWrap(ev));
|
|
131
|
+
await this.within(sub.eose, 'the subscription');
|
|
132
|
+
this.sub = sub;
|
|
133
|
+
void sub.closed.then(() => { if (this.sub === sub)
|
|
134
|
+
this.sub = null; });
|
|
135
|
+
}
|
|
136
|
+
onWrap(ev) {
|
|
137
|
+
if (!ev || typeof ev.id !== 'string' || this.seen.has(ev.id))
|
|
138
|
+
return;
|
|
139
|
+
this.seen.add(ev.id);
|
|
140
|
+
if (this.seen.size > SEEN_MAX)
|
|
141
|
+
this.seen.delete(this.seen.values().next().value);
|
|
142
|
+
let opened;
|
|
143
|
+
try {
|
|
144
|
+
opened = open(ev, { nodeSk: this.opts.nodeSk, agreementSk: this.opts.agreementSk, pubkey: this.pubkey }, (pk) => (pk === this.opts.mediator.pubkey ? this.mediatorAgreement : null), this.reassembler, this.clock());
|
|
145
|
+
}
|
|
146
|
+
catch (e) {
|
|
147
|
+
this.opts.onDrop?.(e.message, ev.id);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (!opened)
|
|
151
|
+
return; // more fragments to come
|
|
152
|
+
const m = opened.message;
|
|
153
|
+
if (Array.isArray(m.please_ack) && (m.please_ack.includes('') || m.please_ack.includes(m.id)) && m.type !== EMPTY_TYPE)
|
|
154
|
+
void this.send({ id: 'ack-' + m.id, type: EMPTY_TYPE, ack: [m.id], body: {} }).catch(() => { });
|
|
155
|
+
if (m.type === EMPTY_TYPE)
|
|
156
|
+
return;
|
|
157
|
+
const waiter = typeof m.thid === 'string' ? this.waiters.get(m.thid) : undefined;
|
|
158
|
+
if (waiter && opened.authenticated && opened.sender === this.opts.mediator.pubkey) {
|
|
159
|
+
this.waiters.delete(m.thid);
|
|
160
|
+
waiter(opened);
|
|
161
|
+
}
|
|
162
|
+
else
|
|
163
|
+
this.opts.onMessage?.(opened);
|
|
164
|
+
}
|
|
165
|
+
/** Seal and publish; throws if the relay took none of the wraps. */
|
|
166
|
+
async send(msg) {
|
|
167
|
+
if (!this.mediatorAgreement)
|
|
168
|
+
throw new SessionError('start() first');
|
|
169
|
+
const wraps = seal(msg, { nodeSk: this.opts.nodeSk, agreementSk: this.opts.agreementSk, pubkey: this.pubkey }, { pubkey: this.opts.mediator.pubkey, agreementPub: this.mediatorAgreement }, { now: this.clock() });
|
|
170
|
+
for (const w of wraps) {
|
|
171
|
+
const r = await this.relay.publish(w);
|
|
172
|
+
if (!r.ok)
|
|
173
|
+
throw new SessionError('the mediator\'s relay refused a wrap: ' + r.message);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/** Send a message and wait for the mediator's answer on its thread. */
|
|
177
|
+
async request(msg) {
|
|
178
|
+
if (!this.connected)
|
|
179
|
+
throw new SessionError('not connected; start() or resume() first');
|
|
180
|
+
const answer = new Promise((resolve) => this.waiters.set(msg.id, resolve));
|
|
181
|
+
try {
|
|
182
|
+
await this.send(msg);
|
|
183
|
+
return (await this.within(answer, msg.type.split('/').pop())).message;
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
this.waiters.delete(msg.id);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
async requestMediation() {
|
|
190
|
+
const reply = await this.request(this.client.buildMediateRequest(this.mediatorDid));
|
|
191
|
+
const r = this.client.recordMediationResponse(reply);
|
|
192
|
+
this.opts.onState?.(this.client.snapshot());
|
|
193
|
+
return r;
|
|
194
|
+
}
|
|
195
|
+
async updateKeylist(add = [], remove = []) {
|
|
196
|
+
const reply = await this.request(this.client.buildKeylistUpdate(this.mediatorDid, add, remove));
|
|
197
|
+
const r = this.client.recordKeylistUpdateResponse(reply);
|
|
198
|
+
this.opts.onState?.(this.client.snapshot());
|
|
199
|
+
return r;
|
|
200
|
+
}
|
|
201
|
+
/** Drain every registered key until the mediator has nothing left, acking
|
|
202
|
+
* each batch so it purges what was taken. maxRounds bounds a mediator that
|
|
203
|
+
* keeps returning the same batch. */
|
|
204
|
+
async pickup(opts = {}) {
|
|
205
|
+
const limit = opts.limit ?? PICKUP_LIMIT_DEFAULT, maxRounds = opts.maxRounds ?? 50;
|
|
206
|
+
// The mediator's own key is always known here, so messages it authcrypts
|
|
207
|
+
// itself open; anyone else needs the caller's resolver.
|
|
208
|
+
const mediatorKid = this.mediatorDid + '#agree';
|
|
209
|
+
const resolve = (skid) => (skid === mediatorKid ? this.mediatorAgreement : opts.resolveSender?.(skid));
|
|
210
|
+
const out = [];
|
|
211
|
+
const taken = new Set();
|
|
212
|
+
for (const first of this.client.buildDeliveryRequests(this.mediatorDid, limit)) {
|
|
213
|
+
let req = first;
|
|
214
|
+
for (let round = 0; round < maxRounds; round++) {
|
|
215
|
+
const batch = this.client.openDelivery(await this.request(req), resolve).filter((d) => !taken.has(d.id));
|
|
216
|
+
if (!batch.length)
|
|
217
|
+
break;
|
|
218
|
+
batch.forEach((d) => taken.add(d.id));
|
|
219
|
+
out.push(...batch);
|
|
220
|
+
// messages-received has no answer; the next drain shows whether it took.
|
|
221
|
+
await this.send(this.client.buildMessagesReceived(this.mediatorDid, batch.map((d) => d.id)));
|
|
222
|
+
if (batch.length < limit)
|
|
223
|
+
break;
|
|
224
|
+
const key = first.body.recipient_key;
|
|
225
|
+
req = this.client.buildDeliveryRequest(this.mediatorDid, limit, key);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
230
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fleetmesh/leaf",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Fleetmesh leaf profile in TypeScript: browsers and PWAs as mediated mesh leaves",
|
|
5
|
+
"license": "CC0-1.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./src/*": "./src/*"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"src"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc --ignoreConfig --target ES2022 --module ESNext --moduleResolution Bundler --lib ES2022,DOM --strict --declaration --rewriteRelativeImportExtensions --outDir dist --rootDir src src/index.ts && node -e \"const fs=require('fs'),path=require('path');const walk=d=>fs.readdirSync(d,{withFileTypes:true}).forEach(e=>{const p=path.join(d,e.name);if(e.isDirectory())walk(p);else if(p.endsWith('.d.ts'))fs.writeFileSync(p,fs.readFileSync(p,'utf8').replace(/\\.ts(['\\\"])/g,'.js$1'))});walk('dist')\"",
|
|
22
|
+
"prepack": "npm run build",
|
|
23
|
+
"test": "vitest run --project node",
|
|
24
|
+
"test:browser": "vitest run --project browser",
|
|
25
|
+
"test:all": "vitest run --project node --project browser",
|
|
26
|
+
"typecheck": "tsc --noEmit",
|
|
27
|
+
"browsers": "playwright install chromium firefox webkit",
|
|
28
|
+
"e2e": "node scripts/e2e-anchor.ts",
|
|
29
|
+
"test:browser-e2e": "vitest run --project browser-e2e",
|
|
30
|
+
"demo": "vite --config vite.demo.config.ts",
|
|
31
|
+
"demo:anchor": "node scripts/demo-anchor.ts"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@noble/ciphers": "2.4.0",
|
|
35
|
+
"@noble/curves": "2.4.0",
|
|
36
|
+
"@noble/hashes": "2.4.0",
|
|
37
|
+
"@scure/base": "2.4.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@types/node": "24.3.0",
|
|
41
|
+
"@vitest/browser-playwright": "5.0.3",
|
|
42
|
+
"playwright": "1.63.0",
|
|
43
|
+
"typescript": "7.0.2",
|
|
44
|
+
"vite": "8.3.2",
|
|
45
|
+
"vitest": "5.0.3"
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// The slices of schema/schema/constants.json this package reads, inlined so a
|
|
2
|
+
// browser bundle needs no JSON loader. test/constants.test.ts holds them equal
|
|
3
|
+
// to the schema, so a change there fails here instead of drifting.
|
|
4
|
+
export const DID = {
|
|
5
|
+
multicodec: { node: 'e701', agreement: 'ec01', transport: 'ed01' },
|
|
6
|
+
peer: {
|
|
7
|
+
service_abbreviations: {
|
|
8
|
+
type: 't',
|
|
9
|
+
serviceEndpoint: 's',
|
|
10
|
+
routingKeys: 'r',
|
|
11
|
+
accept: 'a',
|
|
12
|
+
DIDCommMessaging: 'dm',
|
|
13
|
+
} as Record<string, string>,
|
|
14
|
+
},
|
|
15
|
+
} as const;
|
|
16
|
+
|
|
17
|
+
export const DESCRIPTOR = {
|
|
18
|
+
did_contexts: ['https://www.w3.org/ns/cid/v1', 'https://w3id.org/nostr/context'],
|
|
19
|
+
max_lifetime_seconds_leaf: 86400,
|
|
20
|
+
default_pow_bits: 20,
|
|
21
|
+
required_protocols: ['https://fleetmesh.org/peering/1.0', 'https://fleetmesh.org/budget/1.0'],
|
|
22
|
+
} as const;
|
|
23
|
+
|
|
24
|
+
/** kinds.json#version and schema/DIGEST: what a descriptor's protocol tag names. */
|
|
25
|
+
export const PROTOCOL = {
|
|
26
|
+
version: 'fleetmesh/0.1-draft',
|
|
27
|
+
digest: '695a868c3f2b343dba6f134cc23706bf8e48db392122cce63e06b69b3f92b7a7',
|
|
28
|
+
} as const;
|
|
29
|
+
|
|
30
|
+
export const GRANT = {
|
|
31
|
+
max_clock_skew_seconds: 60,
|
|
32
|
+
} as const;
|
|
33
|
+
|
|
34
|
+
export const LEAF = {
|
|
35
|
+
store_window_days: 30,
|
|
36
|
+
} as const;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// A leaf's own kind 11801 descriptor (meshnode node/protocols/nostr/
|
|
2
|
+
// descriptor.py build(), validated by fleetmesh_core identity.validate_descriptor).
|
|
3
|
+
//
|
|
4
|
+
// An anchor learns how to answer a leaf from this: the agreement key every
|
|
5
|
+
// envelope to the leaf is encrypted to, and the mediator it is reached
|
|
6
|
+
// through. It authenticates the leaf's authcrypt by the same key, looked up
|
|
7
|
+
// on its relays by the leaf's node key, so a leaf publishes this before it
|
|
8
|
+
// asks for anything. A leaf claims no coverage, mediates for nobody, and
|
|
9
|
+
// lives at most a day.
|
|
10
|
+
import { DESCRIPTOR, PROTOCOL } from './constants.ts';
|
|
11
|
+
import { eventId, type NostrEvent, pubkeyOf, signEvent, type Tags } from './event.ts';
|
|
12
|
+
import { multikey } from './keys.ts';
|
|
13
|
+
|
|
14
|
+
export const KIND = 11801;
|
|
15
|
+
export const SOFTWARE: [string, string] = ['https://fleetmesh.org', '0.0.1'];
|
|
16
|
+
|
|
17
|
+
export interface LeafDescriptorOptions {
|
|
18
|
+
/** The leaf's X25519 agreement public key. */
|
|
19
|
+
agreementPub: Uint8Array;
|
|
20
|
+
/** did:nostr of the mediator(s) the leaf is reached through, in preference order. */
|
|
21
|
+
mediators?: string[];
|
|
22
|
+
/** Fleetmesh protocols beyond the two every node declares. */
|
|
23
|
+
protocols?: string[];
|
|
24
|
+
/** The person or org running this leaf; never the leaf's own key. */
|
|
25
|
+
operator?: string;
|
|
26
|
+
now?: number;
|
|
27
|
+
/** Seconds; capped at the leaf maximum. */
|
|
28
|
+
lifetime?: number;
|
|
29
|
+
/** NIP-13 bits to mine. meshnode's builder mines DESCRIPTOR.default_pow_bits,
|
|
30
|
+
* but no anchor checks it yet, and 20 bits is seconds of main-thread work
|
|
31
|
+
* in a browser, so the default is none. */
|
|
32
|
+
powBits?: number;
|
|
33
|
+
content?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Leading zero bits of a 64-hex event id (NIP-13). */
|
|
37
|
+
export function powBits(idHex: string): number {
|
|
38
|
+
if (!/^[0-9a-fA-F]{64}$/.test(idHex)) throw new Error('an event id is 64 hex digits');
|
|
39
|
+
let bits = 0;
|
|
40
|
+
for (const ch of idHex) {
|
|
41
|
+
const n = parseInt(ch, 16);
|
|
42
|
+
if (n === 0) { bits += 4; continue; }
|
|
43
|
+
return bits + Math.clz32(n) - 28;
|
|
44
|
+
}
|
|
45
|
+
return bits;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The reference's mining: ['nonce', n, bits] appended last, n counted up. */
|
|
49
|
+
export function mine(pubkey: string, createdAt: number, kind: number, tags: Tags, content: string, bits: number,
|
|
50
|
+
maxTries = 1 << 26): Tags {
|
|
51
|
+
const base = tags.filter((t) => t[0] !== 'nonce');
|
|
52
|
+
for (let n = 0; n < maxTries; n++) {
|
|
53
|
+
const trial = [...base, ['nonce', String(n), String(bits)]];
|
|
54
|
+
if (powBits(eventId(pubkey, createdAt, kind, trial, content)) >= bits) return trial;
|
|
55
|
+
}
|
|
56
|
+
throw new Error(`no nonce found in ${maxTries} tries`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A signed kind 11801 for a leaf, in the reference builder's tag order. */
|
|
60
|
+
export function buildLeafDescriptor(nodeSk: string, opts: LeafDescriptorOptions): NostrEvent {
|
|
61
|
+
const now = opts.now ?? Math.floor(Date.now() / 1000);
|
|
62
|
+
const pubkey = pubkeyOf(nodeSk);
|
|
63
|
+
if (opts.operator && opts.operator === pubkey) throw new Error('the operator is a person, not the leaf\'s own key');
|
|
64
|
+
const max = DESCRIPTOR.max_lifetime_seconds_leaf;
|
|
65
|
+
const lifetime = Math.min(opts.lifetime ?? max, max);
|
|
66
|
+
const protos = [...new Set([...(opts.protocols ?? []), ...DESCRIPTOR.required_protocols])].sort();
|
|
67
|
+
let tags: Tags = [
|
|
68
|
+
['class', 'leaf'],
|
|
69
|
+
['protocol', PROTOCOL.version, PROTOCOL.digest],
|
|
70
|
+
['software', ...SOFTWARE],
|
|
71
|
+
['key', 'agreement', multikey('agreement', opts.agreementPub)],
|
|
72
|
+
];
|
|
73
|
+
for (const m of opts.mediators ?? []) tags.push(['mediator', m]);
|
|
74
|
+
tags.push(...protos.map((p) => ['c', p]));
|
|
75
|
+
if (opts.operator) tags.push(['operator', opts.operator]);
|
|
76
|
+
tags.push(['expiration', String(now + lifetime)]);
|
|
77
|
+
const content = opts.content ?? '';
|
|
78
|
+
if (opts.powBits) tags = mine(pubkey, now, KIND, tags, content, opts.powBits);
|
|
79
|
+
return signEvent(nodeSk, now, KIND, tags, content);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The agreement Multikey a descriptor names, raw, or null. */
|
|
83
|
+
export function agreementOf(desc: NostrEvent): Uint8Array | null {
|
|
84
|
+
const t = desc.tags.find((x) => x[0] === 'key' && x[1] === 'agreement' && typeof x[2] === 'string');
|
|
85
|
+
if (!t || !/^fec01[0-9a-f]{64}$/.test(t[2]!)) return null;
|
|
86
|
+
const hex = t[2]!.slice(5);
|
|
87
|
+
return Uint8Array.from(hex.match(/../g)!.map((b) => parseInt(b, 16)));
|
|
88
|
+
}
|