@fleetmesh/leaf 0.0.0-stage → 0.1.1

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
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @fleetmesh/leaf
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Fleetmesh **leaf** profile in TypeScript, so browsers and PWAs can join the
4
+ mesh as mediated leaves.
5
+
6
+ A leaf holds one `wss://` connection to its mediator (an anchor), speaks
7
+ gift-wrapped DIDComm v2 over standard Nostr frames, reconciles with NIP-77, and
8
+ keeps a bounded local store. It does not forward, mediate, issue grants or file
9
+ reports. See `fleetmesh.org/spec.html`, "The leaf profile and mobile
10
+ operational limits" and "Mediation is how a phone gets an address".
11
+
12
+ ## Conformance
13
+
14
+ The Python reference in `core/` is the source of truth. Every primitive here is
15
+ tested against `core/vectors/*.json`, read in place through the umbrella
16
+ layout, so this package must be checked out next to `core/`.
17
+
18
+ ```sh
19
+ npm install
20
+ npm test # Node
21
+ npm run typecheck
22
+ ```
23
+
24
+ The same suite runs in the three engines a PWA meets, through vitest browser
25
+ mode on Playwright:
26
+
27
+ ```sh
28
+ npm run browsers # once: Chromium, Firefox and WebKit
29
+ npm run test:browser
30
+ ```
31
+
32
+ Playwright keeps its engines in a shared cache guarded by a lock. If another
33
+ tool's install is holding that lock, give this package a cache of its own by
34
+ setting `PLAYWRIGHT_BROWSERS_PATH` for both commands, e.g.
35
+ `~/Library/Caches/ms-playwright-fleetmesh-leaf`.
36
+
37
+ Dependencies are limited to the audited `@noble/*` and `@scure/base`
38
+ libraries, pinned exactly.
39
+
40
+ ## Negentropy interop
41
+
42
+ `scripts/negentropy-harness.ts` speaks hoytech's negentropy conformance
43
+ protocol (the same one `core`'s `fleetmesh_core.conformance.harness` speaks), so
44
+ `fleetmesh.org/scripts/interop-negentropy.py` can put this port on one end of a
45
+ reconciliation and the Python reference on the other. `src/` uses erasable
46
+ TypeScript only, so Node runs it without a build step:
47
+
48
+ ```sh
49
+ node scripts/negentropy-harness.ts < commands
50
+ ```
51
+
52
+ ## End to end against a real anchor
53
+
54
+ `npm run e2e` starts meshnode's own relay server and a `NodeApp` of class
55
+ anchor on localhost (`scripts/e2e-anchor.py`), then drives a `LeafSession`
56
+ against it over a real WebSocket: descriptor exchange, mediate-request and
57
+ grant, keylist update, forwards buffered by the anchor and drained in
58
+ batches across every registered key, acks purging the inbox, and a
59
+ dropped socket resumed with the mail that arrived meanwhile picked up.
60
+ Needs Python 3 and the umbrella's `meshnode/`, `core/` and `schema/`.
61
+
62
+ The same lifecycle runs inside Chromium, Firefox and WebKit, each leaf on the
63
+ page's own WebSocket and crypto, against one shared anchor that a vitest
64
+ global setup starts (`test-e2e/`):
65
+
66
+ ```sh
67
+ npm run test:browser-e2e
68
+ ```
69
+
70
+ Buffering a forward and reading the anchor's queue are the anchor's side, so
71
+ the page asks for them through vitest browser commands; everything the leaf
72
+ does happens in the browser.
73
+
74
+ ## In a browser: the PWA pieces
75
+
76
+ ```ts
77
+ import { startBrowserLeaf } from '@fleetmesh/leaf';
78
+
79
+ const hub = startBrowserLeaf({ mediator: { pubkey: '<anchor node key>', endpoint: 'wss://anchor.example' } });
80
+ hub.on((e) => { if (e.t === 'delivered') render(e.deliveries); });
81
+ ```
82
+
83
+ - **One connection per origin.** Every tab asks Web Locks for one lock; the
84
+ holder leads and alone runs the session, the others reach it over a
85
+ BroadcastChannel and take over when it closes (`src/pwa/hub.ts`). A
86
+ service worker cannot hold this connection: browsers stop an idle worker
87
+ within about thirty seconds, open socket or not.
88
+ - **IndexedDB** keeps the identity encrypted under a non-extractable
89
+ WebCrypto key, the grant and keylist, the mediator, and an inbox evicted by
90
+ age (`src/pwa/store.ts`).
91
+ - **Foreground networking, push to wake.** The leader drains on launch, when
92
+ the page becomes visible, and when the service worker posts
93
+ `SW_PICKUP` after a Web Push. Anchors do not send pushes yet.
94
+
95
+ `demo/` is a small installable page built on this. Run a real anchor and the
96
+ page side by side:
97
+
98
+ ```sh
99
+ npm run demo:anchor # prints the link to open
100
+ npm run demo
101
+ ```
102
+
103
+ The anchor leaves a numbered hello for every leaf it admits. Open a second
104
+ tab: it follows; close the first: the second takes over.
@@ -0,0 +1,27 @@
1
+ export declare const DID: {
2
+ readonly multicodec: {
3
+ readonly node: 'e701';
4
+ readonly agreement: 'ec01';
5
+ readonly transport: 'ed01';
6
+ };
7
+ readonly peer: {
8
+ readonly service_abbreviations: Record<string, string>;
9
+ };
10
+ };
11
+ export declare const DESCRIPTOR: {
12
+ readonly did_contexts: readonly ['https://www.w3.org/ns/cid/v1', 'https://w3id.org/nostr/context'];
13
+ readonly max_lifetime_seconds_leaf: 86400;
14
+ readonly default_pow_bits: 20;
15
+ readonly required_protocols: readonly ['https://fleetmesh.org/peering/1.0', 'https://fleetmesh.org/budget/1.0'];
16
+ };
17
+ /** kinds.json#version and schema/DIGEST: what a descriptor's protocol tag names. */
18
+ export declare const PROTOCOL: {
19
+ readonly version: 'fleetmesh/0.1-draft';
20
+ readonly digest: '695a868c3f2b343dba6f134cc23706bf8e48db392122cce63e06b69b3f92b7a7';
21
+ };
22
+ export declare const GRANT: {
23
+ readonly max_clock_skew_seconds: 60;
24
+ };
25
+ export declare const LEAF: {
26
+ readonly store_window_days: 30;
27
+ };
@@ -0,0 +1,32 @@
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
+ },
14
+ },
15
+ };
16
+ export const DESCRIPTOR = {
17
+ did_contexts: ['https://www.w3.org/ns/cid/v1', 'https://w3id.org/nostr/context'],
18
+ max_lifetime_seconds_leaf: 86400,
19
+ default_pow_bits: 20,
20
+ required_protocols: ['https://fleetmesh.org/peering/1.0', 'https://fleetmesh.org/budget/1.0'],
21
+ };
22
+ /** kinds.json#version and schema/DIGEST: what a descriptor's protocol tag names. */
23
+ export const PROTOCOL = {
24
+ version: 'fleetmesh/0.1-draft',
25
+ digest: '695a868c3f2b343dba6f134cc23706bf8e48db392122cce63e06b69b3f92b7a7',
26
+ };
27
+ export const GRANT = {
28
+ max_clock_skew_seconds: 60,
29
+ };
30
+ export const LEAF = {
31
+ store_window_days: 30,
32
+ };
@@ -0,0 +1,29 @@
1
+ import { type NostrEvent, type Tags } from './event.ts';
2
+ export declare const KIND = 11801;
3
+ export declare const SOFTWARE: [string, string];
4
+ export interface LeafDescriptorOptions {
5
+ /** The leaf's X25519 agreement public key. */
6
+ agreementPub: Uint8Array;
7
+ /** did:nostr of the mediator(s) the leaf is reached through, in preference order. */
8
+ mediators?: string[];
9
+ /** Fleetmesh protocols beyond the two every node declares. */
10
+ protocols?: string[];
11
+ /** The person or org running this leaf; never the leaf's own key. */
12
+ operator?: string;
13
+ now?: number;
14
+ /** Seconds; capped at the leaf maximum. */
15
+ lifetime?: number;
16
+ /** NIP-13 bits to mine. meshnode's builder mines DESCRIPTOR.default_pow_bits,
17
+ * but no anchor checks it yet, and 20 bits is seconds of main-thread work
18
+ * in a browser, so the default is none. */
19
+ powBits?: number;
20
+ content?: string;
21
+ }
22
+ /** Leading zero bits of a 64-hex event id (NIP-13). */
23
+ export declare function powBits(idHex: string): number;
24
+ /** The reference's mining: ['nonce', n, bits] appended last, n counted up. */
25
+ export declare function mine(pubkey: string, createdAt: number, kind: number, tags: Tags, content: string, bits: number, maxTries?: number): Tags;
26
+ /** A signed kind 11801 for a leaf, in the reference builder's tag order. */
27
+ export declare function buildLeafDescriptor(nodeSk: string, opts: LeafDescriptorOptions): NostrEvent;
28
+ /** The agreement Multikey a descriptor names, raw, or null. */
29
+ export declare function agreementOf(desc: NostrEvent): Uint8Array | null;
@@ -0,0 +1,73 @@
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.js';
11
+ import { eventId, pubkeyOf, signEvent } from './event.js';
12
+ import { multikey } from './keys.js';
13
+ export const KIND = 11801;
14
+ export const SOFTWARE = ['https://fleetmesh.org', '0.0.1'];
15
+ /** Leading zero bits of a 64-hex event id (NIP-13). */
16
+ export function powBits(idHex) {
17
+ if (!/^[0-9a-fA-F]{64}$/.test(idHex))
18
+ throw new Error('an event id is 64 hex digits');
19
+ let bits = 0;
20
+ for (const ch of idHex) {
21
+ const n = parseInt(ch, 16);
22
+ if (n === 0) {
23
+ bits += 4;
24
+ continue;
25
+ }
26
+ return bits + Math.clz32(n) - 28;
27
+ }
28
+ return bits;
29
+ }
30
+ /** The reference's mining: ['nonce', n, bits] appended last, n counted up. */
31
+ export function mine(pubkey, createdAt, kind, tags, content, bits, maxTries = 1 << 26) {
32
+ const base = tags.filter((t) => t[0] !== 'nonce');
33
+ for (let n = 0; n < maxTries; n++) {
34
+ const trial = [...base, ['nonce', String(n), String(bits)]];
35
+ if (powBits(eventId(pubkey, createdAt, kind, trial, content)) >= bits)
36
+ return trial;
37
+ }
38
+ throw new Error(`no nonce found in ${maxTries} tries`);
39
+ }
40
+ /** A signed kind 11801 for a leaf, in the reference builder's tag order. */
41
+ export function buildLeafDescriptor(nodeSk, opts) {
42
+ const now = opts.now ?? Math.floor(Date.now() / 1000);
43
+ const pubkey = pubkeyOf(nodeSk);
44
+ if (opts.operator && opts.operator === pubkey)
45
+ throw new Error('the operator is a person, not the leaf\'s own key');
46
+ const max = DESCRIPTOR.max_lifetime_seconds_leaf;
47
+ const lifetime = Math.min(opts.lifetime ?? max, max);
48
+ const protos = [...new Set([...(opts.protocols ?? []), ...DESCRIPTOR.required_protocols])].sort();
49
+ let tags = [
50
+ ['class', 'leaf'],
51
+ ['protocol', PROTOCOL.version, PROTOCOL.digest],
52
+ ['software', ...SOFTWARE],
53
+ ['key', 'agreement', multikey('agreement', opts.agreementPub)],
54
+ ];
55
+ for (const m of opts.mediators ?? [])
56
+ tags.push(['mediator', m]);
57
+ tags.push(...protos.map((p) => ['c', p]));
58
+ if (opts.operator)
59
+ tags.push(['operator', opts.operator]);
60
+ tags.push(['expiration', String(now + lifetime)]);
61
+ const content = opts.content ?? '';
62
+ if (opts.powBits)
63
+ tags = mine(pubkey, now, KIND, tags, content, opts.powBits);
64
+ return signEvent(nodeSk, now, KIND, tags, content);
65
+ }
66
+ /** The agreement Multikey a descriptor names, raw, or null. */
67
+ export function agreementOf(desc) {
68
+ const t = desc.tags.find((x) => x[0] === 'key' && x[1] === 'agreement' && typeof x[2] === 'string');
69
+ if (!t || !/^fec01[0-9a-f]{64}$/.test(t[2]))
70
+ return null;
71
+ const hex = t[2].slice(5);
72
+ return Uint8Array.from(hex.match(/../g).map((b) => parseInt(b, 16)));
73
+ }
package/dist/did.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ import { type KeyKind } from './keys.ts';
2
+ export interface ServiceEndpoint {
3
+ uri?: string;
4
+ accept?: string[];
5
+ routingKeys?: string[];
6
+ }
7
+ export interface Service {
8
+ id?: string;
9
+ type?: string;
10
+ serviceEndpoint?: ServiceEndpoint | string;
11
+ }
12
+ export interface PeerParts {
13
+ node: string | null;
14
+ agreement: string | null;
15
+ service: Service | null;
16
+ }
17
+ export interface Parsed {
18
+ method: 'nostr' | 'key' | 'peer';
19
+ kind?: KeyKind;
20
+ node: string | null;
21
+ }
22
+ export interface VerificationMethod {
23
+ id: string;
24
+ type: 'Multikey';
25
+ controller: string;
26
+ publicKeyMultibase: string;
27
+ }
28
+ export interface Document {
29
+ '@context': string[];
30
+ id: string;
31
+ alsoKnownAs: string[];
32
+ verificationMethod: VerificationMethod[];
33
+ authentication: string[];
34
+ assertionMethod: string[];
35
+ keyAgreement: string[];
36
+ service: Service[];
37
+ }
38
+ /** A kind 11801 descriptor, as far as this module reads it. */
39
+ export interface Descriptor {
40
+ pubkey: string;
41
+ tags: string[][];
42
+ }
43
+ /** 02 || x: the even-y point BIP-340 x-only keys stand for. */
44
+ export declare function compressedNodeKey(xOnlyHex: string): Uint8Array;
45
+ export declare function didKey(kind: KeyKind, raw: Uint8Array): string;
46
+ /** [kind, raw bytes] of a did:key this profile emits; refuses other codecs. */
47
+ export declare function parseDidKey(did: string): [KeyKind, Uint8Array];
48
+ export declare const nodeDidKey: (xOnlyHex: string) => string;
49
+ /** did:peer:2 of a node: V = the node key, E = the agreement key, S = the DIDComm service. */
50
+ export declare function didPeer(nodePkHex: string, agreementRaw: Uint8Array | null, service: Service | null): string;
51
+ export declare function parseDidPeer(did: string): PeerParts;
52
+ /** {method, node} for any DID this profile speaks; node is the x-only hex when it names one. */
53
+ export declare function parse(did: string): Parsed;
54
+ export declare const didNostr: (pubkey: string) => string;
55
+ /** The 64-hex node pubkey a did:nostr, did:key or did:peer (or a kid of one) names. */
56
+ export declare function nodeOfDid(didOrKid: string): string;
57
+ export declare function didcommService(desc: Descriptor): Service | null;
58
+ /** The node profile a did:nostr resolver emits for a kind 11801, with its aliases. */
59
+ export declare function document(desc: Descriptor): Document;
package/dist/did.js ADDED
@@ -0,0 +1,221 @@
1
+ // DIDs: did:nostr is the identity; did:key and did:peer are derived views of
2
+ // it (core fleetmesh_core/identity/did.py, constants.json#did, profile
3
+ // did-aliases). Neither adds a key, a curve or a trust root.
4
+ //
5
+ // did:key did:key:z<base58btc(multicodec || raw key)>; one per key kind.
6
+ // The node key is secp256k1-pub over the COMPRESSED point
7
+ // (02 || x, even y as BIP-340 implies).
8
+ // did:peer numalgo 2: V = the node key, E = the agreement key, S = the
9
+ // DIDCommMessaging service, abbreviated, base64url-nopad
10
+ // canonical JSON. A snapshot of the descriptor, never the truth.
11
+ import { schnorr } from '@noble/curves/secp256k1.js';
12
+ import { base58 } from '@scure/base';
13
+ import { DESCRIPTOR, DID } from './constants.js';
14
+ import { b64u, b64uDec, bytesToHex, canonicalJson, fromUtf8, hexToBytes, isHex, utf8 } from './encoding.js';
15
+ import { KEY_KINDS, multikey, parseMultikey } from './keys.js';
16
+ const CODEC = {
17
+ node: hexToBytes(DID.multicodec.node),
18
+ agreement: hexToBytes(DID.multicodec.agreement),
19
+ transport: hexToBytes(DID.multicodec.transport),
20
+ };
21
+ const ABBREV = DID.peer.service_abbreviations;
22
+ const UNABBREV = Object.fromEntries(Object.entries(ABBREV).map(([k, v]) => [v, k]));
23
+ const startsWith = (b, p) => b.length >= p.length && p.every((x, i) => b[i] === x);
24
+ /** 02 || x: the even-y point BIP-340 x-only keys stand for. */
25
+ export function compressedNodeKey(xOnlyHex) {
26
+ if (!isHex(xOnlyHex, 64, true))
27
+ throw new Error('a public key is 32 bytes of hex');
28
+ try {
29
+ schnorr.utils.lift_x(BigInt('0x' + xOnlyHex));
30
+ }
31
+ catch {
32
+ throw new Error('not an x-only secp256k1 public key');
33
+ }
34
+ const out = new Uint8Array(33);
35
+ out[0] = 0x02;
36
+ out.set(hexToBytes(xOnlyHex.toLowerCase()), 1);
37
+ return out;
38
+ }
39
+ export function didKey(kind, raw) {
40
+ if (!KEY_KINDS.includes(kind))
41
+ throw new Error('did:key kinds are agreement, node, transport');
42
+ const want = kind === 'node' ? 33 : 32;
43
+ if (raw.length !== want)
44
+ throw new Error(`${kind} key is ${want} bytes`);
45
+ const body = new Uint8Array(CODEC[kind].length + raw.length);
46
+ body.set(CODEC[kind]);
47
+ body.set(raw, CODEC[kind].length);
48
+ return 'did:key:z' + base58.encode(body);
49
+ }
50
+ /** [kind, raw bytes] of a did:key this profile emits; refuses other codecs. */
51
+ export function parseDidKey(did) {
52
+ if (!did.startsWith('did:key:z'))
53
+ throw new Error('did:key is base58btc (z) here');
54
+ let body;
55
+ try {
56
+ body = base58.decode(did.slice('did:key:z'.length));
57
+ }
58
+ catch {
59
+ throw new Error('not base58btc');
60
+ }
61
+ for (const kind of KEY_KINDS) {
62
+ const codec = CODEC[kind];
63
+ if (!startsWith(body, codec))
64
+ continue;
65
+ const raw = body.slice(codec.length);
66
+ if (raw.length !== (kind === 'node' ? 33 : 32))
67
+ throw new Error(`${kind} did:key has the wrong length`);
68
+ if (kind === 'node' && raw[0] !== 0x02)
69
+ throw new Error('node did:key must be the even-y compressed point');
70
+ return [kind, raw];
71
+ }
72
+ throw new Error('a different curve is a different network: codec ' + bytesToHex(body.slice(0, 2)));
73
+ }
74
+ export const nodeDidKey = (xOnlyHex) => didKey('node', compressedNodeKey(xOnlyHex));
75
+ // One value of a did:peer:2 service, abbreviated or expanded. `id` is dropped
76
+ // only at the top level - the one did:peer:2 assigns - never from a nested
77
+ // object, which is somebody else's id.
78
+ function abbrValue(v, table, dropId) {
79
+ if (typeof v === 'string')
80
+ return table[v] ?? v;
81
+ if (Array.isArray(v))
82
+ return v.map((x) => abbrValue(x, table, false));
83
+ if (v && typeof v === 'object') {
84
+ const out = {};
85
+ for (const [k, vv] of Object.entries(v)) {
86
+ if (dropId && k === 'id')
87
+ continue;
88
+ out[table[k] ?? k] = abbrValue(vv, table, false);
89
+ }
90
+ return out;
91
+ }
92
+ return v;
93
+ }
94
+ /** did:peer:2 of a node: V = the node key, E = the agreement key, S = the DIDComm service. */
95
+ export function didPeer(nodePkHex, agreementRaw, service) {
96
+ let out = 'did:peer:2.V' + nodeDidKey(nodePkHex).slice('did:key:'.length);
97
+ if (agreementRaw !== null)
98
+ out += '.E' + didKey('agreement', agreementRaw).slice('did:key:'.length);
99
+ if (service !== null)
100
+ out += '.S' + b64u(utf8(canonicalJson(abbrValue(service, ABBREV, true))));
101
+ return out;
102
+ }
103
+ export function parseDidPeer(did) {
104
+ if (!did.startsWith('did:peer:2.'))
105
+ throw new Error('only did:peer numalgo 2 is spoken here');
106
+ const out = { node: null, agreement: null, service: null };
107
+ for (const el of did.slice('did:peer:2.'.length).split('.')) {
108
+ if (!el)
109
+ throw new Error('empty did:peer:2 element');
110
+ const purpose = el[0], body = el.slice(1);
111
+ if (purpose === 'V') {
112
+ const [kind, raw] = parseDidKey('did:key:' + body);
113
+ if (kind !== 'node')
114
+ throw new Error('V must be the node key');
115
+ out.node = bytesToHex(raw.slice(1));
116
+ }
117
+ else if (purpose === 'E') {
118
+ const [kind, raw] = parseDidKey('did:key:' + body);
119
+ if (kind !== 'agreement')
120
+ throw new Error('E must be the agreement key');
121
+ out.agreement = bytesToHex(raw);
122
+ }
123
+ else if (purpose === 'S') {
124
+ let doc;
125
+ try {
126
+ doc = JSON.parse(fromUtf8(b64uDec(body)));
127
+ }
128
+ catch (e) {
129
+ throw new Error('S element is not JSON: ' + e.message);
130
+ }
131
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc))
132
+ throw new Error('S element must be a JSON object');
133
+ out.service = { ...abbrValue(doc, UNABBREV, false), id: '#didcomm' };
134
+ }
135
+ else {
136
+ throw new Error('unknown did:peer:2 purpose ' + JSON.stringify(purpose));
137
+ }
138
+ }
139
+ if (out.node === null)
140
+ throw new Error('did:peer:2 without a V element names no node');
141
+ return out;
142
+ }
143
+ /** {method, node} for any DID this profile speaks; node is the x-only hex when it names one. */
144
+ export function parse(did) {
145
+ if (did.startsWith('did:nostr:')) {
146
+ const pk = did.slice('did:nostr:'.length);
147
+ compressedNodeKey(pk);
148
+ return { method: 'nostr', node: pk };
149
+ }
150
+ if (did.startsWith('did:key:')) {
151
+ const [kind, raw] = parseDidKey(did);
152
+ return { method: 'key', kind, node: kind === 'node' ? bytesToHex(raw.slice(1)) : null };
153
+ }
154
+ if (did.startsWith('did:peer:'))
155
+ return { method: 'peer', node: parseDidPeer(did).node };
156
+ throw new Error('did methods here are nostr, key and peer');
157
+ }
158
+ export const didNostr = (pubkey) => 'did:nostr:' + pubkey.toLowerCase();
159
+ /** The 64-hex node pubkey a did:nostr, did:key or did:peer (or a kid of one) names. */
160
+ export function nodeOfDid(didOrKid) {
161
+ const body = didOrKid.split('#', 1)[0];
162
+ if (body.startsWith('did:nostr:')) {
163
+ const pk = body.slice('did:nostr:'.length).toLowerCase();
164
+ if (isHex(pk, 64))
165
+ return pk;
166
+ }
167
+ const node = parse(body).node;
168
+ if (!node)
169
+ throw new Error(`DID ${JSON.stringify(didOrKid)} names no node pubkey`);
170
+ return node;
171
+ }
172
+ const tagsNamed = (desc, name) => desc.tags.filter((t) => t.length && t[0] === name);
173
+ const byPriority = (a, b) => (a.length > 3 ? +a[3] : 50) - (b.length > 3 ? +b[3] : 50);
174
+ export function didcommService(desc) {
175
+ const wss = tagsNamed(desc, 'endpoint').sort(byPriority).filter((e) => e[1] === 'wss' || e[1] === 'https');
176
+ if (!wss.length)
177
+ return null;
178
+ const se = { uri: wss[0][2], accept: ['didcomm/v2'] };
179
+ const med = tagsNamed(desc, 'mediator');
180
+ if (med.length)
181
+ se.routingKeys = [med[0][1] + '#agree'];
182
+ return { id: '#didcomm', type: 'DIDCommMessaging', serviceEndpoint: se };
183
+ }
184
+ /** The node profile a did:nostr resolver emits for a kind 11801, with its aliases. */
185
+ export function document(desc) {
186
+ const did = 'did:nostr:' + desc.pubkey;
187
+ const vm = [
188
+ { id: '#nostr', type: 'Multikey', controller: did, publicKeyMultibase: multikey('node', hexToBytes(desc.pubkey)) },
189
+ ];
190
+ let agreementName = null;
191
+ let agreementRaw = null;
192
+ for (const k of tagsNamed(desc, 'key')) {
193
+ const name = { agreement: '#agree', transport: '#wire' }[k[1]];
194
+ if (!name)
195
+ throw new Error('unknown key tag ' + JSON.stringify(k[1]));
196
+ vm.push({ id: name, type: 'Multikey', controller: did, publicKeyMultibase: k[2] });
197
+ if (k[1] === 'agreement') {
198
+ agreementName = name;
199
+ agreementRaw = parseMultikey(k[2])[1];
200
+ }
201
+ }
202
+ const service = didcommService(desc);
203
+ const services = service ? [service] : [];
204
+ const caps = new Set(tagsNamed(desc, 'c').map((t) => t[1]));
205
+ for (const e of tagsNamed(desc, 'endpoint').sort(byPriority)) {
206
+ if (e[1] === 'wss' && caps.has('relay'))
207
+ services.push({ id: '#relay', type: 'NostrRelay', serviceEndpoint: e[2] });
208
+ else if (e[1] === 'iroh')
209
+ services.push({ id: '#iroh', type: 'IrohNode', serviceEndpoint: e[2] });
210
+ }
211
+ return {
212
+ '@context': [...DESCRIPTOR.did_contexts],
213
+ id: did,
214
+ alsoKnownAs: [nodeDidKey(desc.pubkey), didPeer(desc.pubkey, agreementRaw, service)],
215
+ verificationMethod: vm,
216
+ authentication: ['#nostr'],
217
+ assertionMethod: ['#nostr'],
218
+ keyAgreement: agreementName ? [agreementName] : [],
219
+ service: services,
220
+ };
221
+ }
@@ -0,0 +1,59 @@
1
+ export declare const TYP = "application/didcomm-encrypted+json";
2
+ export declare const ENC = "A256CBC-HS512";
3
+ export declare const AUTHCRYPT = "ECDH-1PU+A256KW";
4
+ export declare const ANONCRYPT = "ECDH-ES+A256KW";
5
+ export interface JWERecipient {
6
+ header: {
7
+ kid: string;
8
+ };
9
+ encrypted_key: string;
10
+ }
11
+ export interface JWE {
12
+ protected: string;
13
+ recipients: JWERecipient[];
14
+ iv: string;
15
+ ciphertext: string;
16
+ tag: string;
17
+ }
18
+ export interface ProtectedHeader {
19
+ alg: string;
20
+ enc: string;
21
+ typ?: string;
22
+ apv?: string;
23
+ apu?: string;
24
+ skid?: string;
25
+ epk?: {
26
+ kty?: string;
27
+ crv?: string;
28
+ x?: string;
29
+ };
30
+ }
31
+ export declare class EnvelopeError extends Error {
32
+ }
33
+ /** X25519 agreement; refuses the all-zero secret a low-order point yields. */
34
+ export declare function x25519Shared(priv: Uint8Array, theirPub: Uint8Array): Uint8Array;
35
+ export declare const agreementPublic: (priv: Uint8Array) => Uint8Array;
36
+ /** NIST SP 800-56A one-step KDF, SHA-256, one round (every key here is <= 256 bits). */
37
+ export declare function concatKdf(z: Uint8Array, alg: string, apu: Uint8Array, apv: Uint8Array, keydatalenBits: number, cctag?: Uint8Array): Uint8Array;
38
+ /** RFC 7518 5.2.5. The CEK is 64 bytes: MAC key first, then the AES key. */
39
+ export declare function cbcHs512Encrypt(cek: Uint8Array, iv: Uint8Array, plaintext: Uint8Array, aad: Uint8Array): [Uint8Array, Uint8Array];
40
+ export declare function cbcHs512Decrypt(cek: Uint8Array, iv: Uint8Array, ct: Uint8Array, tag: Uint8Array, aad: Uint8Array): Uint8Array;
41
+ /** ECDH-1PU key-wrapping KEK: Z = Ze || Zs, tag in the KDF. */
42
+ export declare const kek1pu: (alg: string, ze: Uint8Array, zs: Uint8Array, apu: Uint8Array, apv: Uint8Array, tag: Uint8Array) => Uint8Array<ArrayBufferLike>;
43
+ export declare const kekEs: (alg: string, ze: Uint8Array, apu: Uint8Array, apv: Uint8Array) => Uint8Array<ArrayBufferLike>;
44
+ /** DIDComm v2: SHA-256 of the sorted recipient kids joined by '.'. */
45
+ export declare const apvFor: (kids: string[]) => Uint8Array;
46
+ export interface EncryptOptions {
47
+ /** [skid, X25519 private key] for authcrypt; absent for anoncrypt. */
48
+ sender?: [string, Uint8Array];
49
+ /** For vectors only; a leaf never passes these. */
50
+ ephPriv?: Uint8Array;
51
+ cek?: Uint8Array;
52
+ iv?: Uint8Array;
53
+ }
54
+ /** A JWE for one plaintext message to [kid, X25519 public key] recipients. */
55
+ export declare function encrypt(message: unknown, recipients: [string, Uint8Array][], opts?: EncryptOptions): JWE;
56
+ /** Open a JWE addressed to myKid: [message, skid or null]. For authcrypt,
57
+ * resolveSender(skid) must return the sender's static X25519 public key; the
58
+ * sender is then authenticated by the agreement itself. */
59
+ export declare function decrypt(jwe: JWE, myKid: string, myPriv: Uint8Array, resolveSender?: (skid: string) => Uint8Array | null | undefined): [any, string | null];