@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,176 @@
1
+ // DIDComm v2 encrypted envelopes (core fleetmesh_core/identity/didcomm.py):
2
+ //
3
+ // authcrypt alg ECDH-1PU+A256KW, enc A256CBC-HS512. The sender's static
4
+ // key is in the agreement, so the recipient knows who wrote it.
5
+ // Every message after first contact.
6
+ // anoncrypt alg ECDH-ES+A256KW, enc A256CBC-HS512. First contact only.
7
+ //
8
+ // JWE JSON serialisation, general form, one or more recipients, all over
9
+ // X25519. The Concat KDF is NIST SP 800-56A one-step with SHA-256 as RFC 7518
10
+ // uses it; ECDH-1PU adds the sender's static agreement to Z and, in
11
+ // key-wrapping mode, the content tag to the KDF input so a recipient cannot
12
+ // re-target the message.
13
+ import { aeskw, cbc } from '@noble/ciphers/aes.js';
14
+ import { x25519 } from '@noble/curves/ed25519.js';
15
+ import { concatBytes, equalBytes, randomBytes } from '@noble/curves/utils.js';
16
+ import { hmac } from '@noble/hashes/hmac.js';
17
+ import { sha256, sha512 } from '@noble/hashes/sha2.js';
18
+ import { b64u, b64uDec, canonicalJson, fromUtf8, utf8 } from './encoding.js';
19
+ export const TYP = 'application/didcomm-encrypted+json';
20
+ export const ENC = 'A256CBC-HS512';
21
+ export const AUTHCRYPT = 'ECDH-1PU+A256KW';
22
+ export const ANONCRYPT = 'ECDH-ES+A256KW';
23
+ const KEK_BITS = { A128KW: 128, A192KW: 192, A256KW: 256 };
24
+ export class EnvelopeError extends Error {
25
+ }
26
+ const u32 = (n) => Uint8Array.of(n >>> 24, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff);
27
+ const len32 = (b) => concatBytes(u32(b.length), b);
28
+ /** X25519 agreement; refuses the all-zero secret a low-order point yields. */
29
+ export function x25519Shared(priv, theirPub) {
30
+ let z;
31
+ try {
32
+ z = x25519.getSharedSecret(priv, theirPub);
33
+ }
34
+ catch (e) {
35
+ throw new EnvelopeError('X25519 agreement failed: ' + e.message);
36
+ }
37
+ if (z.every((b) => b === 0))
38
+ throw new EnvelopeError('X25519 agreement is all zero');
39
+ return z;
40
+ }
41
+ export const agreementPublic = (priv) => x25519.getPublicKey(priv);
42
+ /** NIST SP 800-56A one-step KDF, SHA-256, one round (every key here is <= 256 bits). */
43
+ export function concatKdf(z, alg, apu, apv, keydatalenBits, cctag) {
44
+ const suppPub = concatBytes(u32(keydatalenBits), cctag ? len32(cctag) : new Uint8Array(0));
45
+ const fixed = concatBytes(len32(utf8(alg)), len32(apu), len32(apv), suppPub);
46
+ return sha256(concatBytes(u32(1), z, fixed)).slice(0, keydatalenBits / 8);
47
+ }
48
+ function macOf(macKey, aad, iv, ct) {
49
+ const al = new Uint8Array(8);
50
+ new DataView(al.buffer).setBigUint64(0, BigInt(aad.length) * 8n);
51
+ return hmac(sha512, macKey, concatBytes(aad, iv, ct, al)).slice(0, 32);
52
+ }
53
+ /** RFC 7518 5.2.5. The CEK is 64 bytes: MAC key first, then the AES key. */
54
+ export function cbcHs512Encrypt(cek, iv, plaintext, aad) {
55
+ if (cek.length !== 64 || iv.length !== 16)
56
+ throw new EnvelopeError('A256CBC-HS512 needs a 64-byte CEK and a 16-byte IV');
57
+ const ct = cbc(cek.subarray(32), iv).encrypt(plaintext);
58
+ return [ct, macOf(cek.subarray(0, 32), aad, iv, ct)];
59
+ }
60
+ export function cbcHs512Decrypt(cek, iv, ct, tag, aad) {
61
+ if (cek.length !== 64 || iv.length !== 16)
62
+ throw new EnvelopeError('A256CBC-HS512 needs a 64-byte CEK and a 16-byte IV');
63
+ if (!equalBytes(tag, macOf(cek.subarray(0, 32), aad, iv, ct)))
64
+ throw new EnvelopeError('authentication tag does not verify');
65
+ try {
66
+ return cbc(cek.subarray(32), iv).decrypt(ct);
67
+ }
68
+ catch (e) {
69
+ throw new EnvelopeError('ciphertext does not decrypt: ' + e.message);
70
+ }
71
+ }
72
+ const kekBits = (alg) => KEK_BITS[alg.split('+')[1]];
73
+ /** ECDH-1PU key-wrapping KEK: Z = Ze || Zs, tag in the KDF. */
74
+ export const kek1pu = (alg, ze, zs, apu, apv, tag) => concatKdf(concatBytes(ze, zs), alg, apu, apv, kekBits(alg), tag);
75
+ export const kekEs = (alg, ze, apu, apv) => concatKdf(ze, alg, apu, apv, kekBits(alg));
76
+ /** DIDComm v2: SHA-256 of the sorted recipient kids joined by '.'. */
77
+ export const apvFor = (kids) => sha256(utf8([...kids].sort().join('.')));
78
+ /** A JWE for one plaintext message to [kid, X25519 public key] recipients. */
79
+ export function encrypt(message, recipients, opts = {}) {
80
+ if (!recipients.length)
81
+ throw new EnvelopeError('a message needs a recipient');
82
+ const { sender } = opts;
83
+ const body = utf8(canonicalJson(message));
84
+ const ephPriv = opts.ephPriv ?? x25519.utils.randomSecretKey();
85
+ const apv = apvFor(recipients.map(([k]) => k));
86
+ const alg = sender ? AUTHCRYPT : ANONCRYPT;
87
+ const prot = {
88
+ alg, enc: ENC, typ: TYP, apv: b64u(apv),
89
+ epk: { kty: 'OKP', crv: 'X25519', x: b64u(agreementPublic(ephPriv)) },
90
+ };
91
+ let apu = new Uint8Array(0);
92
+ if (sender) {
93
+ prot.skid = sender[0];
94
+ prot.apu = b64u(utf8(sender[0]));
95
+ apu = utf8(sender[0]);
96
+ }
97
+ const protectedB64 = b64u(utf8(canonicalJson(prot)));
98
+ const cek = opts.cek ?? randomBytes(64);
99
+ const iv = opts.iv ?? randomBytes(16);
100
+ const [ct, tag] = cbcHs512Encrypt(cek, iv, body, utf8(protectedB64));
101
+ const recs = recipients.map(([kid, pub]) => {
102
+ const ze = x25519Shared(ephPriv, pub);
103
+ const kek = sender ? kek1pu(alg, ze, x25519Shared(sender[1], pub), apu, apv, tag) : kekEs(alg, ze, apu, apv);
104
+ return { header: { kid }, encrypted_key: b64u(aeskw(kek).encrypt(cek)) };
105
+ });
106
+ return { protected: protectedB64, recipients: recs, iv: b64u(iv), ciphertext: b64u(ct), tag: b64u(tag) };
107
+ }
108
+ const dec = (s, what) => {
109
+ if (typeof s !== 'string')
110
+ throw new EnvelopeError(`${what} is missing`);
111
+ try {
112
+ return b64uDec(s);
113
+ }
114
+ catch {
115
+ throw new EnvelopeError(`${what} is not base64url`);
116
+ }
117
+ };
118
+ /** Open a JWE addressed to myKid: [message, skid or null]. For authcrypt,
119
+ * resolveSender(skid) must return the sender's static X25519 public key; the
120
+ * sender is then authenticated by the agreement itself. */
121
+ export function decrypt(jwe, myKid, myPriv, resolveSender) {
122
+ let prot;
123
+ try {
124
+ prot = JSON.parse(fromUtf8(b64uDec(jwe.protected)));
125
+ }
126
+ catch {
127
+ throw new EnvelopeError('protected header is not JSON');
128
+ }
129
+ const { alg, enc } = prot;
130
+ if (enc !== ENC || (alg !== AUTHCRYPT && alg !== ANONCRYPT))
131
+ throw new EnvelopeError(`unsupported alg/enc ${alg}/${enc}`);
132
+ const rec = (jwe.recipients ?? []).find((r) => r?.header?.kid === myKid);
133
+ if (!rec)
134
+ throw new EnvelopeError('not addressed to ' + myKid);
135
+ const epk = prot.epk ?? {};
136
+ if (epk.kty !== 'OKP' || epk.crv !== 'X25519')
137
+ throw new EnvelopeError('epk must be an X25519 OKP key');
138
+ const ephPub = dec(epk.x, 'epk');
139
+ if (ephPub.length !== 32)
140
+ throw new EnvelopeError('epk is not an X25519 key');
141
+ const apv = prot.apv === undefined ? new Uint8Array(0) : dec(prot.apv, 'apv');
142
+ const apu = prot.apu === undefined ? new Uint8Array(0) : dec(prot.apu, 'apu');
143
+ const tag = dec(jwe.tag, 'tag'), iv = dec(jwe.iv, 'iv'), ct = dec(jwe.ciphertext, 'ciphertext');
144
+ const wrapped = dec(rec.encrypted_key, 'encrypted_key');
145
+ const ze = x25519Shared(myPriv, ephPub);
146
+ let skid = null;
147
+ let kek;
148
+ if (alg === AUTHCRYPT) {
149
+ skid = prot.skid ?? null;
150
+ if (!skid || !resolveSender)
151
+ throw new EnvelopeError('authcrypt needs a skid and a way to resolve it');
152
+ if (!equalBytes(apu, utf8(skid)))
153
+ throw new EnvelopeError('apu does not name the skid');
154
+ const senderPub = resolveSender(skid);
155
+ if (!senderPub)
156
+ throw new EnvelopeError('unknown sender ' + skid);
157
+ kek = kek1pu(alg, ze, x25519Shared(myPriv, senderPub), apu, apv, tag);
158
+ }
159
+ else {
160
+ kek = kekEs(alg, ze, apu, apv);
161
+ }
162
+ let cek;
163
+ try {
164
+ cek = aeskw(kek).decrypt(wrapped);
165
+ }
166
+ catch {
167
+ throw new EnvelopeError('key unwrap failed: wrong recipient key or tampered envelope');
168
+ }
169
+ const body = cbcHs512Decrypt(cek, iv, ct, tag, utf8(jwe.protected));
170
+ try {
171
+ return [JSON.parse(fromUtf8(body)), skid];
172
+ }
173
+ catch {
174
+ throw new EnvelopeError('plaintext is not a JSON message');
175
+ }
176
+ }
@@ -0,0 +1,14 @@
1
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js';
2
+ export { bytesToHex, hexToBytes };
3
+ export declare const utf8: (s: string) => Uint8Array;
4
+ export declare const fromUtf8: (b: Uint8Array) => string;
5
+ /** A string of exactly `length` hex digits; lowercase only unless `upper`. */
6
+ export declare function isHex(value: unknown, length?: number, upper?: boolean): value is string;
7
+ export declare function b64u(b: Uint8Array): string;
8
+ /** Strict base64url without padding: the alphabet only, and canonical (no
9
+ * trailing bits), so two strings never decode to the same bytes. */
10
+ export declare function b64uDec(s: string): Uint8Array;
11
+ /** Canonical JSON: sorted keys, no whitespace, non-ASCII left as is. Numbers
12
+ * must be integers: Python spells 1.0 as "1.0" and JS as "1", so a float
13
+ * cannot be made to agree and is refused. */
14
+ export declare function canonicalJson(v: unknown): string;
@@ -0,0 +1,68 @@
1
+ // Byte and text spellings shared by every module: hex, strict base64url and
2
+ // the canonical JSON the Python reference writes with
3
+ // json.dumps(sort_keys=True, separators=(',', ':'), ensure_ascii=False).
4
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js';
5
+ export { bytesToHex, hexToBytes };
6
+ const utf8Enc = new TextEncoder();
7
+ const utf8Dec = new TextDecoder('utf-8', { fatal: true });
8
+ export const utf8 = (s) => utf8Enc.encode(s);
9
+ export const fromUtf8 = (b) => utf8Dec.decode(b);
10
+ /** A string of exactly `length` hex digits; lowercase only unless `upper`. */
11
+ export function isHex(value, length, upper = false) {
12
+ if (typeof value !== 'string' || !value)
13
+ return false;
14
+ if (length !== undefined && value.length !== length)
15
+ return false;
16
+ return (upper ? /^[0-9a-fA-F]+$/ : /^[0-9a-f]+$/).test(value);
17
+ }
18
+ const B64URL = /^[A-Za-z0-9_-]*$/;
19
+ export function b64u(b) {
20
+ let s = '';
21
+ for (const byte of b)
22
+ s += String.fromCharCode(byte);
23
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
24
+ }
25
+ /** Strict base64url without padding: the alphabet only, and canonical (no
26
+ * trailing bits), so two strings never decode to the same bytes. */
27
+ export function b64uDec(s) {
28
+ if (!B64URL.test(s) || s.length % 4 === 1)
29
+ throw new Error('not base64url');
30
+ const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4));
31
+ const out = new Uint8Array(bin.length);
32
+ for (let i = 0; i < bin.length; i++)
33
+ out[i] = bin.charCodeAt(i);
34
+ if (b64u(out) !== s)
35
+ throw new Error('not canonical base64url');
36
+ return out;
37
+ }
38
+ // Python sorts keys by code point; JS's default sort is by UTF-16 unit, which
39
+ // differs above the BMP.
40
+ function byCodePoint(a, b) {
41
+ const x = [...a], y = [...b];
42
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
43
+ const d = x[i].codePointAt(0) - y[i].codePointAt(0);
44
+ if (d)
45
+ return d;
46
+ }
47
+ return x.length - y.length;
48
+ }
49
+ /** Canonical JSON: sorted keys, no whitespace, non-ASCII left as is. Numbers
50
+ * must be integers: Python spells 1.0 as "1.0" and JS as "1", so a float
51
+ * cannot be made to agree and is refused. */
52
+ export function canonicalJson(v) {
53
+ if (v === null || typeof v === 'boolean' || typeof v === 'string')
54
+ return JSON.stringify(v);
55
+ if (typeof v === 'number') {
56
+ if (!Number.isSafeInteger(v))
57
+ throw new Error('canonical JSON carries integers only');
58
+ return String(v);
59
+ }
60
+ if (Array.isArray(v))
61
+ return '[' + v.map((el) => canonicalJson(el === undefined ? null : el)).join(',') + ']';
62
+ if (typeof v === 'object') {
63
+ const o = v;
64
+ return '{' + Object.keys(o).filter((k) => o[k] !== undefined).sort(byCodePoint)
65
+ .map((k) => JSON.stringify(k) + ':' + canonicalJson(o[k])).join(',') + '}';
66
+ }
67
+ throw new Error('not JSON: ' + typeof v);
68
+ }
@@ -0,0 +1,22 @@
1
+ export type Tags = string[][];
2
+ export interface UnsignedEvent {
3
+ pubkey: string;
4
+ created_at: number;
5
+ kind: number;
6
+ tags: Tags;
7
+ content: string;
8
+ }
9
+ export interface NostrEvent extends UnsignedEvent {
10
+ id: string;
11
+ sig: string;
12
+ }
13
+ export declare function eventId(pubkey: string, createdAt: number, kind: number, tags: Tags, content: string): string;
14
+ export declare const pubkeyOf: (skHex: string) => string;
15
+ /** A complete signed event. `aux` is BIP-340's auxiliary randomness: random
16
+ * by default; the reference signs with 32 zero bytes, which tests pass to
17
+ * reproduce its signatures. */
18
+ export declare function signEvent(skHex: string, createdAt: number, kind: number, tags?: Tags, content?: string, aux?: Uint8Array): NostrEvent;
19
+ /** Every NIP-01 field with the right primitive type. */
20
+ export declare function isEventShaped(o: unknown): o is NostrEvent;
21
+ /** False for anything malformed; never throws. */
22
+ export declare function verifyEvent(ev: unknown): boolean;
package/dist/event.js ADDED
@@ -0,0 +1,42 @@
1
+ // NIP-01 events (core fleetmesh_core/storage/store.py): the id is sha256 over
2
+ // the serialised [0, pubkey, created_at, kind, tags, content], and the
3
+ // signature is BIP-340 over that id by the event's pubkey.
4
+ import { schnorr } from '@noble/curves/secp256k1.js';
5
+ import { randomBytes } from '@noble/curves/utils.js';
6
+ import { sha256 } from '@noble/hashes/sha2.js';
7
+ import { bytesToHex, hexToBytes, isHex, utf8 } from './encoding.js';
8
+ // JSON.stringify of this array is the NIP-01 serialisation, and the one
9
+ // Python's json.dumps(separators=(',', ':'), ensure_ascii=False) writes.
10
+ export function eventId(pubkey, createdAt, kind, tags, content) {
11
+ return bytesToHex(sha256(utf8(JSON.stringify([0, pubkey, createdAt, kind, tags, content]))));
12
+ }
13
+ export const pubkeyOf = (skHex) => bytesToHex(schnorr.getPublicKey(hexToBytes(skHex)));
14
+ /** A complete signed event. `aux` is BIP-340's auxiliary randomness: random
15
+ * by default; the reference signs with 32 zero bytes, which tests pass to
16
+ * reproduce its signatures. */
17
+ export function signEvent(skHex, createdAt, kind, tags = [], content = '', aux = randomBytes(32)) {
18
+ const pubkey = pubkeyOf(skHex);
19
+ const id = eventId(pubkey, createdAt, kind, tags, content);
20
+ const sig = bytesToHex(schnorr.sign(hexToBytes(id), hexToBytes(skHex), aux));
21
+ return { id, pubkey, created_at: createdAt, kind, tags, content, sig };
22
+ }
23
+ /** Every NIP-01 field with the right primitive type. */
24
+ export function isEventShaped(o) {
25
+ if (!o || typeof o !== 'object')
26
+ return false;
27
+ const e = o;
28
+ return typeof e.id === 'string' && typeof e.pubkey === 'string' && Number.isSafeInteger(e.created_at)
29
+ && Number.isSafeInteger(e.kind) && Array.isArray(e.tags) && typeof e.content === 'string' && typeof e.sig === 'string';
30
+ }
31
+ /** False for anything malformed; never throws. */
32
+ export function verifyEvent(ev) {
33
+ if (!isEventShaped(ev) || !isHex(ev.pubkey, 64) || !isHex(ev.id, 64) || ev.created_at < 0)
34
+ return false;
35
+ try {
36
+ const want = eventId(ev.pubkey, ev.created_at, ev.kind, ev.tags, ev.content);
37
+ return ev.id === want && isHex(ev.sig, 128) && schnorr.verify(hexToBytes(ev.sig), hexToBytes(want), hexToBytes(ev.pubkey));
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
@@ -0,0 +1,29 @@
1
+ import { type NostrEvent } from './event.js;
2
+ export declare const SEAL = 13;
3
+ export declare const WRAP_LIVE = 21059;
4
+ export declare const WRAP_STORED = 1059;
5
+ export declare const TWO_DAYS: number;
6
+ export declare const SKEW_MAX: number;
7
+ export declare const RETENTION: number;
8
+ export declare class GiftWrapError extends Error {
9
+ }
10
+ /** The source of the skew, the one-time key and both nonces, drawn in the
11
+ * reference's order, so the same rng yields the reference's bytes. */
12
+ export type Rng = (n: number) => Uint8Array;
13
+ export interface WrapOptions {
14
+ kind?: number;
15
+ rng?: Rng;
16
+ /** BIP-340 aux for both signatures; fresh random per signature when absent.
17
+ * The reference signs with 32 zero bytes, which parity tests pass. */
18
+ aux?: Uint8Array;
19
+ }
20
+ /** Live: now. Stored: skewed. The rng is drawn either way, as the reference
21
+ * does, so the same rng yields the same bytes. */
22
+ export declare function wrapCreatedAt(now: number, kind: number, rng: Rng): number;
23
+ /** Wrap any JSON payload (a DIDComm JWE here) from sender to recipient. */
24
+ export declare function wrap(payload: unknown, senderSk: string, recipientPk: string, now: number, { kind, rng, aux }?: WrapOptions): NostrEvent;
25
+ /** [payload, senderPk]. Every layer is checked: the wrap's signature and
26
+ * addressing, the seal's signature, and that the seal's author is the key
27
+ * the inner ciphertext was agreed with. With `now`, both dates must lie in
28
+ * the retention window; without it age is not judged. */
29
+ export declare function unwrap(wrapEvent: NostrEvent, recipientSk: string, now?: number): [unknown, string];
@@ -0,0 +1,100 @@
1
+ // NIP-59 gift wraps (core fleetmesh_core/crypto/giftwrap.py): the control
2
+ // transport that always works, and the one a leaf uses to its mediator.
3
+ //
4
+ // A DIDComm envelope travels as the content of a kind 13 seal signed by the
5
+ // sender, itself the content of a kind 21059 wrap signed by a key used once.
6
+ // Both layers are nip44/2 to the recipient's node key. Kind 1059 is the
7
+ // stored variant, for store-and-forward.
8
+ //
9
+ // The seal's created_at, and a stored wrap's, are skewed into the past so a
10
+ // relay keeping the wrap cannot line messages up by time. A live wrap is
11
+ // dated now: relays drop an ephemeral event older than about a minute.
12
+ import { randomBytes } from '@noble/curves/utils.js';
13
+ import { GRANT } from './constants.js';
14
+ import { bytesToHex, canonicalJson } from './encoding.js';
15
+ import { pubkeyOf, signEvent, verifyEvent } from './event.js';
16
+ import * as nip44 from './nip44.js';
17
+ export const SEAL = 13;
18
+ export const WRAP_LIVE = 21059;
19
+ export const WRAP_STORED = 1059;
20
+ export const TWO_DAYS = 2 * 86400;
21
+ // The skew stops twice the clock tolerance short of a receiver's two-day
22
+ // `since`, so a sender whose clock is behind never lands outside it.
23
+ export const SKEW_MAX = TWO_DAYS - 2 * GRANT.max_clock_skew_seconds;
24
+ // How long a wrap or seal stays openable: a week past the skew, for a node
25
+ // that was down. Older is a wrap being replayed from a store.
26
+ export const RETENTION = 7 * 86400;
27
+ export class GiftWrapError extends Error {
28
+ }
29
+ function skew(now, rng) {
30
+ const b = rng(4);
31
+ const n = ((b[0] << 24) >>> 0) + (b[1] << 16) + (b[2] << 8) + b[3];
32
+ return now - (n % (SKEW_MAX + 1));
33
+ }
34
+ /** Live: now. Stored: skewed. The rng is drawn either way, as the reference
35
+ * does, so the same rng yields the same bytes. */
36
+ export function wrapCreatedAt(now, kind, rng) {
37
+ const skewed = skew(now, rng);
38
+ return kind === WRAP_LIVE ? now : skewed;
39
+ }
40
+ /** Wrap any JSON payload (a DIDComm JWE here) from sender to recipient. */
41
+ export function wrap(payload, senderSk, recipientPk, now, { kind = WRAP_LIVE, rng = randomBytes, aux } = {}) {
42
+ if (kind !== WRAP_LIVE && kind !== WRAP_STORED)
43
+ throw new GiftWrapError('a wrap is kind 21059 or kind 1059');
44
+ const body = canonicalJson(payload);
45
+ try {
46
+ const conv = nip44.conversationKey(senderSk, recipientPk);
47
+ const sealAt = skew(now, rng);
48
+ const seal = signEvent(senderSk, sealAt, SEAL, [], nip44.encrypt(body, conv, rng(32)), aux ?? randomBytes(32));
49
+ const once = bytesToHex(rng(32));
50
+ const convW = nip44.conversationKey(once, recipientPk);
51
+ const at = wrapCreatedAt(now, kind, rng);
52
+ return signEvent(once, at, kind, [['p', recipientPk]], nip44.encrypt(canonicalJson(seal), convW, rng(32)), aux ?? randomBytes(32));
53
+ }
54
+ catch (e) {
55
+ if (!(e instanceof nip44.Nip44Error))
56
+ throw e;
57
+ throw new GiftWrapError(`a payload of ${body.length} bytes does not fit one wrap (${e.message}); fragment it`);
58
+ }
59
+ }
60
+ function inDate(ev, now, what) {
61
+ if (now === undefined)
62
+ return;
63
+ const created = ev.created_at;
64
+ if (typeof created !== 'number' || !Number.isSafeInteger(created))
65
+ throw new GiftWrapError(`${what} has no created_at`);
66
+ if (created < now - SKEW_MAX - RETENTION)
67
+ throw new GiftWrapError(`${what} is older than ${SKEW_MAX + RETENTION} seconds`);
68
+ if (created > now + SKEW_MAX)
69
+ throw new GiftWrapError(`${what} is dated more than ${SKEW_MAX} seconds ahead`);
70
+ }
71
+ function open(content, conv, what) {
72
+ try {
73
+ return JSON.parse(nip44.decrypt(content, conv));
74
+ }
75
+ catch (e) {
76
+ throw new GiftWrapError(`${what} does not open: ${e.message}`);
77
+ }
78
+ }
79
+ /** [payload, senderPk]. Every layer is checked: the wrap's signature and
80
+ * addressing, the seal's signature, and that the seal's author is the key
81
+ * the inner ciphertext was agreed with. With `now`, both dates must lie in
82
+ * the retention window; without it age is not judged. */
83
+ export function unwrap(wrapEvent, recipientSk, now) {
84
+ const myPk = pubkeyOf(recipientSk);
85
+ if (wrapEvent.kind !== WRAP_LIVE && wrapEvent.kind !== WRAP_STORED)
86
+ throw new GiftWrapError('not a gift wrap');
87
+ inDate(wrapEvent, now, 'wrap');
88
+ if (!(wrapEvent.tags ?? []).some((t) => t[0] === 'p' && t[1] === myPk))
89
+ throw new GiftWrapError('not addressed to me');
90
+ if (!verifyEvent(wrapEvent))
91
+ throw new GiftWrapError('wrap signature does not verify');
92
+ const seal = open(wrapEvent.content, nip44.conversationKey(recipientSk, wrapEvent.pubkey), 'wrap');
93
+ if (!seal || typeof seal !== 'object' || seal.kind !== SEAL || (Array.isArray(seal.tags) ? seal.tags.length : seal.tags))
94
+ throw new GiftWrapError('inner event is not a seal');
95
+ if (!verifyEvent(seal))
96
+ throw new GiftWrapError('seal signature does not verify');
97
+ inDate(seal, now, 'seal');
98
+ const payload = open(seal.content, nip44.conversationKey(recipientSk, seal.pubkey), 'seal');
99
+ return [payload, seal.pubkey];
100
+ }
@@ -0,0 +1,17 @@
1
+ export * as descriptor from './descriptor.js;
2
+ export * as did from './did.js;
3
+ export * as didcomm from './didcomm.js;
4
+ export * as encoding from './encoding.js;
5
+ export * as event from './event.js;
6
+ export * as giftwrap from './giftwrap.js;
7
+ export * as keys from './keys.js;
8
+ export * as mediation from './mediation/leaf.js;
9
+ export * as mediationMessages from './mediation/messages.js;
10
+ export * as negentropy from './negentropy.js;
11
+ export * as nip44 from './nip44.js;
12
+ export * as relay from './relay.js;
13
+ export * as seal from './seal.js;
14
+ export { LeafSession, type LeafSessionOptions, SessionError } from './session.js;
15
+ export { type BrowserLeafOptions, startBrowserLeaf, SW_PICKUP } from './pwa/browser-leaf.js;
16
+ export { type HubEvent, LeafHub, type LeafStatus } from './pwa/hub.js;
17
+ export { LeafStore } from './pwa/store.js;
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ // @fleetmesh/leaf: the leaf profile (spec § "The leaf profile and mobile
2
+ // operational limits") for browsers and PWAs. One wss:// connection to a
3
+ // mediator, gift-wrapped DIDComm, NIP-77 range reconciliation, a bounded store.
4
+ export * as descriptor from './descriptor.js';
5
+ export * as did from './did.js';
6
+ export * as didcomm from './didcomm.js';
7
+ export * as encoding from './encoding.js';
8
+ export * as event from './event.js';
9
+ export * as giftwrap from './giftwrap.js';
10
+ export * as keys from './keys.js';
11
+ export * as mediation from './mediation/leaf.js';
12
+ export * as mediationMessages from './mediation/messages.js';
13
+ export * as negentropy from './negentropy.js';
14
+ export * as nip44 from './nip44.js';
15
+ export * as relay from './relay.js';
16
+ export * as seal from './seal.js';
17
+ export { LeafSession, SessionError } from './session.js';
18
+ export { startBrowserLeaf, SW_PICKUP } from './pwa/browser-leaf.js';
19
+ export { LeafHub } from './pwa/hub.js';
20
+ export { LeafStore } from './pwa/store.js';
package/dist/keys.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export type KeyKind = 'node' | 'agreement' | 'transport';
2
+ export declare const KEY_KINDS: readonly KeyKind[];
3
+ export declare const PREFIX: Record<KeyKind, string>;
4
+ export declare function multikey(kind: KeyKind, raw: Uint8Array): string;
5
+ /** [kind, raw 32 bytes]. Rejects anything that is not one of the three. */
6
+ export declare function parseMultikey(s: string): [KeyKind, Uint8Array];
package/dist/keys.js ADDED
@@ -0,0 +1,31 @@
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.js';
13
+ export const KEY_KINDS = ['node', 'agreement', 'transport'];
14
+ export const PREFIX = { node: 'fe70102', agreement: 'fec01', transport: 'fed01' };
15
+ export function multikey(kind, raw) {
16
+ if (!KEY_KINDS.includes(kind) || raw.length !== 32)
17
+ throw new Error('a Multikey here is node, agreement or transport over 32 bytes');
18
+ let hex = '';
19
+ for (const b of raw)
20
+ hex += b.toString(16).padStart(2, '0');
21
+ return PREFIX[kind] + hex;
22
+ }
23
+ /** [kind, raw 32 bytes]. Rejects anything that is not one of the three. */
24
+ export function parseMultikey(s) {
25
+ for (const kind of KEY_KINDS) {
26
+ const p = PREFIX[kind];
27
+ if (s.startsWith(p) && s.length === p.length + 64)
28
+ return [kind, hexToBytes(s.slice(p.length))];
29
+ }
30
+ throw new Error('not a fleetmesh Multikey: ' + JSON.stringify(s.slice(0, 12)));
31
+ }
@@ -0,0 +1,121 @@
1
+ import { type NostrEvent } from '../event.js;
2
+ import { type ForwardBody, type KeylistUpdateBody, type KeylistUpdateResponseBody, type MediateDenyBody, type MediateGrantBody, type Message, type PickupDeliveryBody, type PickupDeliveryRequestBody, type PickupMessagesReceivedBody } from './messages.js;
3
+ /** NIP-66 / kind 11801 query a leaf with no peers sends to bootstrap relays. */
4
+ export declare const DESCRIPTOR_KIND = 11801;
5
+ export declare const COLD_START_FILTER: {
6
+ readonly kinds: readonly [11801];
7
+ readonly '#c': readonly ['mediator'];
8
+ };
9
+ export declare class MediationError extends Error {
10
+ }
11
+ export interface MediationGrantInfo {
12
+ routing_keys: string[];
13
+ endpoint: string | null;
14
+ granted_at: number;
15
+ }
16
+ export interface MediatorCandidate {
17
+ descriptor: NostrEvent;
18
+ /** did:nostr of the anchor: the DID the leaf addresses mediation to. */
19
+ did: string;
20
+ /** The preferred wss:// endpoint (lowest priority number). */
21
+ endpoint: string;
22
+ /** The operator the descriptor names, or the anchor's own key when it names none. */
23
+ operator: string;
24
+ }
25
+ export interface DiscoverOptions {
26
+ requiredCount?: number;
27
+ requireDistinctOperators?: boolean;
28
+ /** Refuse descriptors whose signature does not verify. Default true: a
29
+ * leaf reads these off public relays, where anyone can publish one naming
30
+ * a real anchor's key beside their own endpoint. */
31
+ verify?: boolean;
32
+ /** Unix seconds; when given, descriptors past their `expiration` are refused. */
33
+ now?: number;
34
+ /** Accept ws:// as well as wss://. For local development only: a page
35
+ * served over https cannot open ws://, and nothing on it is private. */
36
+ allowInsecure?: boolean;
37
+ }
38
+ /** Select independent mediator anchors from kind 11801 descriptors, in the
39
+ * order given (the Three-Layer Operator Independence Model): each carries
40
+ * ['c', 'mediator'] and a WebSocket endpoint, and, by default, no two share
41
+ * an operator. */
42
+ export declare function discoverMediators(descriptors: Iterable<NostrEvent>, opts?: DiscoverOptions): MediatorCandidate[];
43
+ /** The two secrets a leaf holds: its node key (secp256k1, the did:nostr
44
+ * subject; signs its events and seals its wraps) and its agreement key
45
+ * (X25519, opens every envelope addressed to #agree). */
46
+ export interface LeafKeys {
47
+ nodePk: string;
48
+ agreementSk: Uint8Array;
49
+ }
50
+ export interface OpenedEnvelope {
51
+ attachment: string;
52
+ message: unknown;
53
+ skid: string | null;
54
+ }
55
+ export interface OpenedDelivery {
56
+ id: string;
57
+ sender: string;
58
+ recipient_key: string;
59
+ enqueued_at: number;
60
+ envelopes: OpenedEnvelope[];
61
+ /** Attachments that would not open, with why. The message is still acked:
62
+ * an envelope that does not open now never will, and leaving it in the
63
+ * inbox only makes every later drain return it again. */
64
+ errors: {
65
+ attachment: string;
66
+ error: string;
67
+ }[];
68
+ }
69
+ /** What a leaf must remember between launches: plain JSON, no secrets. */
70
+ export interface LeafClientState {
71
+ mediators: [string, MediationGrantInfo][];
72
+ denied: [string, string][];
73
+ keylists: [string, string[]][];
74
+ }
75
+ /** One leaf's mediation state across its mediators. */
76
+ export declare class LeafClient {
77
+ readonly did: string;
78
+ readonly kid: string;
79
+ readonly mediators: Map<string, MediationGrantInfo>;
80
+ readonly denied: Map<string, string>;
81
+ /** Recipient keys registered with each mediator. The anchor registers the
82
+ * leaf's own DID on admission; keylist updates add and remove the rest. */
83
+ readonly keylists: Map<string, Set<string>>;
84
+ private readonly keys;
85
+ private readonly pending;
86
+ private readonly clock;
87
+ constructor(keys: LeafKeys, clock?: () => number);
88
+ private track;
89
+ /** The pending request a response answers: by thid, from the mediator it was sent to. */
90
+ private answering;
91
+ isGranted: (mediatorDid: string) => boolean;
92
+ /** Grants, denials and keylists, for storage. Pending requests are not
93
+ * kept: an answer to a request from a previous launch is unsolicited. */
94
+ snapshot(): LeafClientState;
95
+ /** Replace this client's state with a snapshot. */
96
+ restore(state: LeafClientState): void;
97
+ buildMediateRequest(mediatorDid: string): Message<Record<string, never>>;
98
+ /** A mediate-grant or mediate-deny answering one of this leaf's requests. */
99
+ recordMediationResponse(msg: Message<MediateGrantBody | MediateDenyBody>): 'granted' | 'denied';
100
+ buildKeylistUpdate(mediatorDid: string, add?: string[], remove?: string[]): Message<KeylistUpdateBody>;
101
+ /** Apply what the mediator says it did; a key it did not mention is unchanged. */
102
+ recordKeylistUpdateResponse(msg: Message<KeylistUpdateResponseBody>): KeylistUpdateResponseBody['updated'];
103
+ buildDeliveryRequest(mediatorDid: string, limit?: number, recipientKey?: string): Message<PickupDeliveryRequestBody>;
104
+ /** One delivery-request per recipient key registered with this mediator.
105
+ * meshnode's MediatorService narrows an unnamed drain to the leaf's own DID
106
+ * (its default target is always in the keylist), so mail sent to any other
107
+ * registered key only comes out when that key is named. Asking per key
108
+ * drains everything from that anchor, and from one that reads an unnamed
109
+ * drain as all keys. */
110
+ buildDeliveryRequests(mediatorDid: string, limit?: number): Message<PickupDeliveryRequestBody>[];
111
+ /** Open a delivery: every attachment's inner JWE, addressed to this leaf's
112
+ * #agree key. resolveSender maps an authcrypt skid to that sender's X25519
113
+ * key; without it only anoncrypt envelopes open. */
114
+ openDelivery(msg: Message<PickupDeliveryBody>, resolveSender?: (skid: string) => Uint8Array | null | undefined): OpenedDelivery[];
115
+ /** messages-received for a drained batch, so the mediator purges it. */
116
+ buildMessagesReceived(mediatorDid: string, ids: string[]): Message<PickupMessagesReceivedBody>;
117
+ /** Wrap an inner encrypted envelope in a routing/2.0 forward to the
118
+ * recipient leaf's mediator. */
119
+ wrapForward(innerEnvelope: string | object, mediatorDid: string, recipientLeafDid: string): Message<ForwardBody>;
120
+ private requireGrant;
121
+ }