@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,137 @@
1
+ const rid = () => Math.random().toString(36).slice(2) + Date.now().toString(36);
2
+ export class LeafHub {
3
+ role = 'follower';
4
+ status = 'idle';
5
+ opts;
6
+ channel;
7
+ listeners = new Set();
8
+ calls = new Map();
9
+ leader = null;
10
+ release = null;
11
+ abort = new AbortController();
12
+ constructor(opts) {
13
+ this.opts = opts;
14
+ const name = opts.name ?? 'fleetmesh-leaf';
15
+ this.channel = new BroadcastChannel(name);
16
+ this.channel.onmessage = (e) => this.onWire(e.data);
17
+ if (!('locks' in navigator))
18
+ throw new Error('this browser has no Web Locks API');
19
+ navigator.locks.request(name + ':connection', { signal: this.abort.signal }, () => this.becomeLeader())
20
+ .catch((e) => { if (e.name !== 'AbortError')
21
+ this.setStatus('error', String(e)); });
22
+ }
23
+ on(fn) {
24
+ this.listeners.add(fn);
25
+ return () => this.listeners.delete(fn);
26
+ }
27
+ emit(e) {
28
+ for (const fn of this.listeners)
29
+ fn(e);
30
+ }
31
+ /** The leader reports status; every tab hears it. */
32
+ setStatus(status, detail) {
33
+ this.status = status;
34
+ const e = detail === undefined ? { t: 'status', status } : { t: 'status', status, detail };
35
+ this.emit(e);
36
+ if (this.role === 'leader')
37
+ this.channel.postMessage(e);
38
+ }
39
+ /** The leader announces deliveries; every tab hears them. */
40
+ announce(deliveries) {
41
+ if (!deliveries.length)
42
+ return;
43
+ const e = { t: 'delivered', deliveries };
44
+ this.emit(e);
45
+ this.channel.postMessage(e);
46
+ }
47
+ async becomeLeader() {
48
+ this.role = 'leader';
49
+ this.emit({ t: 'role', role: 'leader' });
50
+ const held = new Promise((r) => (this.release = r));
51
+ try {
52
+ this.setStatus('connecting');
53
+ this.leader = await this.opts.lead(this);
54
+ this.setStatus('connected');
55
+ }
56
+ catch (e) {
57
+ this.setStatus('error', e.message);
58
+ }
59
+ await held; // the lock is ours until stop() or the tab goes
60
+ this.leader?.close();
61
+ this.leader = null;
62
+ }
63
+ /** Drain the mediator: here if this tab leads, else through the leader. */
64
+ async pickup() {
65
+ if (this.role === 'leader') {
66
+ if (!this.leader)
67
+ throw new Error('the leader is not connected');
68
+ const got = await this.leader.pickup();
69
+ this.announce(got);
70
+ return got;
71
+ }
72
+ return this.call('pickup');
73
+ }
74
+ /** The leader's status, asked of it (a follower's own copy may be stale). */
75
+ async leaderStatus() {
76
+ return this.role === 'leader' ? this.status : this.call('status');
77
+ }
78
+ call(op) {
79
+ const id = rid();
80
+ return new Promise((resolve, reject) => {
81
+ const timer = setTimeout(() => {
82
+ this.calls.delete(id);
83
+ reject(new Error(`no leader answered ${op} in ${this.opts.timeoutMs ?? 20000}ms`));
84
+ }, this.opts.timeoutMs ?? 20000);
85
+ this.calls.set(id, { resolve, reject, timer });
86
+ this.channel.postMessage({ t: 'call', id, op });
87
+ });
88
+ }
89
+ async onWire(m) {
90
+ if (!m || typeof m !== 'object')
91
+ return;
92
+ if (m.t === 'call') {
93
+ if (this.role !== 'leader')
94
+ return;
95
+ try {
96
+ const value = m.op === 'pickup' ? await this.pickup() : this.status;
97
+ this.channel.postMessage({ t: 'reply', id: m.id, ok: true, value });
98
+ }
99
+ catch (e) {
100
+ this.channel.postMessage({ t: 'reply', id: m.id, ok: false, error: e.message });
101
+ }
102
+ }
103
+ else if (m.t === 'reply') {
104
+ const c = this.calls.get(m.id);
105
+ if (!c)
106
+ return;
107
+ clearTimeout(c.timer);
108
+ this.calls.delete(m.id);
109
+ if (m.ok)
110
+ c.resolve(m.value);
111
+ else
112
+ c.reject(new Error(m.error));
113
+ }
114
+ else if (m.t === 'status') {
115
+ if (this.role === 'follower') {
116
+ this.status = m.status;
117
+ this.emit(m);
118
+ }
119
+ }
120
+ else if (m.t === 'delivered') {
121
+ this.emit(m);
122
+ }
123
+ }
124
+ /** Leave: a leader gives up the lock (the next tab takes over), a follower its place in line. */
125
+ stop() {
126
+ this.abort.abort();
127
+ this.release?.();
128
+ this.release = null;
129
+ this.role = 'follower';
130
+ for (const c of this.calls.values()) {
131
+ clearTimeout(c.timer);
132
+ c.reject(new Error('hub stopped'));
133
+ }
134
+ this.calls.clear();
135
+ this.channel.close();
136
+ }
137
+ }
@@ -0,0 +1,39 @@
1
+ import type { LeafClientState, OpenedDelivery } from '../mediation/leaf.js;
2
+ export declare const DB_NAME = "fleetmesh-leaf";
3
+ export interface LeafIdentity {
4
+ nodeSk: string;
5
+ agreementSk: Uint8Array;
6
+ }
7
+ export interface MediatorConfig {
8
+ pubkey: string;
9
+ endpoint: string;
10
+ }
11
+ export interface StoredDelivery extends OpenedDelivery {
12
+ received_at: number;
13
+ }
14
+ export declare class LeafStore {
15
+ readonly db: IDBDatabase;
16
+ private readonly now;
17
+ private constructor();
18
+ static open(name?: string, now?: () => number): Promise<LeafStore>;
19
+ close(): void;
20
+ /** Ask the browser not to evict this origin's storage under pressure. */
21
+ static persist(): Promise<boolean>;
22
+ private get;
23
+ private put;
24
+ private wrappingKey;
25
+ /** This leaf's keys, created on first use. Only the encrypted form is stored. */
26
+ identity(): Promise<LeafIdentity>;
27
+ /** Forget this leaf entirely: keys, grants, inbox. */
28
+ reset(): Promise<void>;
29
+ state: () => Promise<LeafClientState | undefined>;
30
+ saveState: (s: LeafClientState) => Promise<void>;
31
+ mediator: () => Promise<MediatorConfig | undefined>;
32
+ saveMediator: (m: MediatorConfig) => Promise<void>;
33
+ /** Keep deliveries and return the ones that were new; an id already held
34
+ * is kept as first received. Then evict past the window. */
35
+ addToInbox(deliveries: OpenedDelivery[]): Promise<OpenedDelivery[]>;
36
+ inbox(): Promise<StoredDelivery[]>;
37
+ /** Drop what is older than the leaf's store window. */
38
+ evict(windowDays?: number): Promise<number>;
39
+ }
@@ -0,0 +1,157 @@
1
+ // What a browser leaf keeps between launches, in IndexedDB:
2
+ //
3
+ // identity the node key and agreement key, AES-GCM-encrypted under a
4
+ // non-extractable WebCrypto key stored beside them. Script on
5
+ // this origin can still use that key - nothing in a browser can
6
+ // stop that - but the raw secrets are never at rest in the
7
+ // clear, and nothing can export them.
8
+ // state LeafClient.snapshot(): grants, denials, keylists.
9
+ // config which mediator, at which endpoint.
10
+ // inbox opened deliveries, a rolling window by age (constants.json
11
+ // leaf.store_window_days). Eviction is by age, never by request.
12
+ //
13
+ // A leaf's node key is its network identity, kept apart from any personal
14
+ // social key (spec: "keys in the OS keystore"); in a browser the closest
15
+ // thing is a key the page can use and not read.
16
+ import { schnorr } from '@noble/curves/secp256k1.js';
17
+ import { LEAF } from '../constants.js';
18
+ import { bytesToHex, fromUtf8, hexToBytes, utf8 } from '../encoding.js';
19
+ export const DB_NAME = 'fleetmesh-leaf';
20
+ const VERSION = 1;
21
+ const KV = 'kv', INBOX = 'inbox';
22
+ function req(r) {
23
+ return new Promise((resolve, reject) => {
24
+ r.onsuccess = () => resolve(r.result);
25
+ r.onerror = () => reject(r.error);
26
+ });
27
+ }
28
+ function done(tx) {
29
+ return new Promise((resolve, reject) => {
30
+ tx.oncomplete = () => resolve();
31
+ tx.onerror = () => reject(tx.error);
32
+ tx.onabort = () => reject(tx.error ?? new Error('transaction aborted'));
33
+ });
34
+ }
35
+ export class LeafStore {
36
+ db;
37
+ now;
38
+ constructor(db, now) {
39
+ this.db = db;
40
+ this.now = now;
41
+ }
42
+ static async open(name = DB_NAME, now = () => Math.floor(Date.now() / 1000)) {
43
+ const r = indexedDB.open(name, VERSION);
44
+ r.onupgradeneeded = () => {
45
+ const db = r.result;
46
+ if (!db.objectStoreNames.contains(KV))
47
+ db.createObjectStore(KV);
48
+ if (!db.objectStoreNames.contains(INBOX))
49
+ db.createObjectStore(INBOX, { keyPath: 'id' }).createIndex('received_at', 'received_at');
50
+ };
51
+ return new LeafStore(await req(r), now);
52
+ }
53
+ close() {
54
+ this.db.close();
55
+ }
56
+ /** Ask the browser not to evict this origin's storage under pressure. */
57
+ static async persist() {
58
+ try {
59
+ return (await navigator.storage?.persist?.()) ?? false;
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ async get(key) {
66
+ return req(this.db.transaction(KV).objectStore(KV).get(key));
67
+ }
68
+ async put(key, value) {
69
+ const tx = this.db.transaction(KV, 'readwrite');
70
+ tx.objectStore(KV).put(value, key);
71
+ await done(tx);
72
+ }
73
+ // ---- identity ----------------------------------------------------------
74
+ async wrappingKey() {
75
+ const have = await this.get('wrapping-key');
76
+ if (have)
77
+ return have;
78
+ const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
79
+ // Two tabs racing here would each make a key; add() lets only one win.
80
+ const tx = this.db.transaction(KV, 'readwrite');
81
+ tx.objectStore(KV).add(key, 'wrapping-key');
82
+ try {
83
+ await done(tx);
84
+ return key;
85
+ }
86
+ catch {
87
+ return (await this.get('wrapping-key'));
88
+ }
89
+ }
90
+ /** This leaf's keys, created on first use. Only the encrypted form is stored. */
91
+ async identity() {
92
+ const key = await this.wrappingKey();
93
+ const sealed = await this.get('identity');
94
+ if (sealed) {
95
+ const plain = JSON.parse(fromUtf8(new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: sealed.iv }, key, sealed.ct))));
96
+ return { nodeSk: plain.nodeSk, agreementSk: hexToBytes(plain.agreementSk) };
97
+ }
98
+ const id = {
99
+ nodeSk: bytesToHex(schnorr.utils.randomSecretKey()),
100
+ agreementSk: crypto.getRandomValues(new Uint8Array(32)),
101
+ };
102
+ const iv = crypto.getRandomValues(new Uint8Array(12));
103
+ const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, utf8(JSON.stringify({ nodeSk: id.nodeSk, agreementSk: bytesToHex(id.agreementSk) })));
104
+ const tx = this.db.transaction(KV, 'readwrite');
105
+ tx.objectStore(KV).add({ iv, ct }, 'identity');
106
+ try {
107
+ await done(tx);
108
+ return id;
109
+ }
110
+ catch {
111
+ return this.identity(); // another tab made it first; use theirs
112
+ }
113
+ }
114
+ /** Forget this leaf entirely: keys, grants, inbox. */
115
+ async reset() {
116
+ const tx = this.db.transaction([KV, INBOX], 'readwrite');
117
+ tx.objectStore(KV).clear();
118
+ tx.objectStore(INBOX).clear();
119
+ await done(tx);
120
+ }
121
+ // ---- state and config --------------------------------------------------
122
+ state = () => this.get('state');
123
+ saveState = (s) => this.put('state', s);
124
+ mediator = () => this.get('mediator');
125
+ saveMediator = (m) => this.put('mediator', m);
126
+ // ---- inbox -------------------------------------------------------------
127
+ /** Keep deliveries and return the ones that were new; an id already held
128
+ * is kept as first received. Then evict past the window. */
129
+ async addToInbox(deliveries) {
130
+ const now = this.now();
131
+ const tx = this.db.transaction(INBOX, 'readwrite');
132
+ const os = tx.objectStore(INBOX);
133
+ const added = [];
134
+ for (const d of deliveries) {
135
+ const r = os.add({ ...d, received_at: now });
136
+ r.onsuccess = () => added.push(d);
137
+ // Already held: not an error, and must not abort or fail the transaction.
138
+ r.onerror = (e) => { e.preventDefault(); e.stopPropagation(); };
139
+ }
140
+ await done(tx);
141
+ await this.evict();
142
+ return added;
143
+ }
144
+ async inbox() {
145
+ return req(this.db.transaction(INBOX).objectStore(INBOX).index('received_at').getAll());
146
+ }
147
+ /** Drop what is older than the leaf's store window. */
148
+ async evict(windowDays = LEAF.store_window_days) {
149
+ const cutoff = this.now() - windowDays * 86400;
150
+ const tx = this.db.transaction(INBOX, 'readwrite');
151
+ const keys = await req(tx.objectStore(INBOX).index('received_at').getAllKeys(IDBKeyRange.upperBound(cutoff, true)));
152
+ for (const k of keys)
153
+ tx.objectStore(INBOX).delete(k);
154
+ await done(tx);
155
+ return keys.length;
156
+ }
157
+ }
@@ -0,0 +1,67 @@
1
+ import type { NostrEvent } from './event.js;
2
+ /** The slice of the WHATWG WebSocket this module uses. */
3
+ export interface SocketLike {
4
+ readonly readyState: number;
5
+ send(data: string): void;
6
+ close(code?: number, reason?: string): void;
7
+ onopen: ((ev: unknown) => void) | null;
8
+ onmessage: ((ev: {
9
+ data: unknown;
10
+ }) => void) | null;
11
+ onclose: ((ev: unknown) => void) | null;
12
+ onerror: ((ev: unknown) => void) | null;
13
+ }
14
+ export type SocketFactory = (url: string) => SocketLike;
15
+ export type Filter = Record<string, unknown>;
16
+ export interface RelayOptions {
17
+ socket?: SocketFactory;
18
+ /** Sign a NIP-42 kind 22242 for this challenge; without it AUTH is never answered. */
19
+ signAuth?: (challenge: string, relayUrl: string) => NostrEvent;
20
+ timeoutMs?: number;
21
+ onNotice?: (message: string) => void;
22
+ onClose?: () => void;
23
+ }
24
+ export interface PublishResult {
25
+ ok: boolean;
26
+ message: string;
27
+ }
28
+ export interface Subscription {
29
+ readonly id: string;
30
+ /** Resolves on EOSE: the relay has registered the filters and replayed what it holds. */
31
+ readonly eose: Promise<void>;
32
+ /** Resolves with the reason if the relay closes it. */
33
+ readonly closed: Promise<string>;
34
+ close(): void;
35
+ }
36
+ export declare class RelayError extends Error {
37
+ }
38
+ export declare class RelayConnection {
39
+ readonly url: string;
40
+ private readonly opts;
41
+ private ws;
42
+ private challenge;
43
+ private authed;
44
+ private readonly oks;
45
+ private readonly subs;
46
+ private seq;
47
+ constructor(url: string, opts?: RelayOptions);
48
+ get connected(): boolean;
49
+ connect(): Promise<void>;
50
+ close(): void;
51
+ private get timeout();
52
+ private dropped;
53
+ private send;
54
+ /** EVENT, resolved by the relay's OK. Retries once after AUTH when the relay says auth-required. */
55
+ publish(ev: NostrEvent): Promise<PublishResult>;
56
+ private publishOnce;
57
+ /** REQ. Events arrive on onEvent until close(); a relay that closes it for
58
+ * auth-required is answered and asked once more. */
59
+ subscribe(filters: Filter[], onEvent: (ev: NostrEvent) => void): Subscription;
60
+ /** Answer the relay's NIP-42 challenge; false if there is none or no signer. */
61
+ authenticate(): Promise<boolean>;
62
+ private publishAuth;
63
+ private onFrame;
64
+ private endSub;
65
+ }
66
+ /** A NIP-42 auth event for a relay's challenge, signed by the leaf's node key. */
67
+ export declare function authEvent(sign: (createdAt: number, kind: number, tags: string[][], content: string) => NostrEvent, challenge: string, relayUrl: string, now?: number): NostrEvent;
package/dist/relay.js ADDED
@@ -0,0 +1,232 @@
1
+ export class RelayError extends Error {
2
+ }
3
+ const OPEN = 1;
4
+ const defaultSocket = (url) => {
5
+ const WS = globalThis.WebSocket;
6
+ if (!WS)
7
+ throw new RelayError('no WebSocket in this runtime; pass options.socket');
8
+ return new WS(url);
9
+ };
10
+ export class RelayConnection {
11
+ url;
12
+ opts;
13
+ ws = null;
14
+ challenge = null;
15
+ authed = null;
16
+ oks = new Map();
17
+ subs = new Map();
18
+ seq = 0;
19
+ constructor(url, opts = {}) {
20
+ this.url = url;
21
+ this.opts = opts;
22
+ }
23
+ get connected() {
24
+ return this.ws?.readyState === OPEN;
25
+ }
26
+ connect() {
27
+ if (this.connected)
28
+ return Promise.resolve();
29
+ const ws = (this.opts.socket ?? defaultSocket)(this.url);
30
+ this.ws = ws;
31
+ return new Promise((resolve, reject) => {
32
+ let opened = false;
33
+ const timer = setTimeout(() => {
34
+ reject(new RelayError(`no connection to ${this.url} in ${this.timeout}ms`));
35
+ ws.close();
36
+ }, this.timeout);
37
+ ws.onopen = () => {
38
+ opened = true;
39
+ clearTimeout(timer);
40
+ resolve();
41
+ };
42
+ ws.onerror = () => {
43
+ clearTimeout(timer);
44
+ reject(new RelayError('could not connect to ' + this.url));
45
+ };
46
+ ws.onclose = () => {
47
+ clearTimeout(timer);
48
+ if (!opened)
49
+ reject(new RelayError('connection closed before opening'));
50
+ this.dropped();
51
+ };
52
+ ws.onmessage = (ev) => this.onFrame(ev.data);
53
+ });
54
+ }
55
+ close() {
56
+ const ws = this.ws;
57
+ this.ws = null;
58
+ if (ws) {
59
+ ws.onclose = null;
60
+ ws.close();
61
+ }
62
+ this.dropped();
63
+ }
64
+ get timeout() {
65
+ return this.opts.timeoutMs ?? 5000;
66
+ }
67
+ dropped() {
68
+ for (const [id, p] of this.oks) {
69
+ clearTimeout(p.timer);
70
+ p.resolve({ ok: false, message: 'error: connection closed' });
71
+ this.oks.delete(id);
72
+ }
73
+ for (const [id, s] of this.subs) {
74
+ s.closed('error: connection closed');
75
+ this.subs.delete(id);
76
+ }
77
+ this.challenge = null;
78
+ this.authed = null;
79
+ this.opts.onClose?.();
80
+ }
81
+ send(frame) {
82
+ if (!this.ws || !this.connected)
83
+ throw new RelayError('not connected to ' + this.url);
84
+ this.ws.send(JSON.stringify(frame));
85
+ }
86
+ /** EVENT, resolved by the relay's OK. Retries once after AUTH when the relay says auth-required. */
87
+ async publish(ev) {
88
+ const r = await this.publishOnce(ev);
89
+ if (!r.ok && r.message.startsWith('auth-required:') && (await this.authenticate()))
90
+ return this.publishOnce(ev);
91
+ return r;
92
+ }
93
+ publishOnce(ev) {
94
+ return new Promise((resolve) => {
95
+ const timer = setTimeout(() => {
96
+ this.oks.delete(ev.id);
97
+ resolve({ ok: false, message: `error: no OK in ${this.timeout}ms` });
98
+ }, this.timeout);
99
+ this.oks.set(ev.id, { resolve, timer });
100
+ try {
101
+ this.send(['EVENT', ev]);
102
+ }
103
+ catch (e) {
104
+ clearTimeout(timer);
105
+ this.oks.delete(ev.id);
106
+ resolve({ ok: false, message: 'error: ' + e.message });
107
+ }
108
+ });
109
+ }
110
+ /** REQ. Events arrive on onEvent until close(); a relay that closes it for
111
+ * auth-required is answered and asked once more. */
112
+ subscribe(filters, onEvent) {
113
+ const id = 'leaf-' + (++this.seq).toString(36);
114
+ let eose, closed;
115
+ const eoseP = new Promise((r) => (eose = r));
116
+ const closedP = new Promise((r) => (closed = r));
117
+ this.subs.set(id, { filters, onEvent, eose, closed, authRetried: false });
118
+ this.send(['REQ', id, ...filters]);
119
+ return {
120
+ id, eose: eoseP, closed: closedP,
121
+ close: () => {
122
+ if (this.subs.delete(id) && this.connected)
123
+ this.send(['CLOSE', id]);
124
+ },
125
+ };
126
+ }
127
+ /** Answer the relay's NIP-42 challenge; false if there is none or no signer. */
128
+ authenticate() {
129
+ if (this.authed)
130
+ return this.authed;
131
+ if (!this.challenge || !this.opts.signAuth)
132
+ return Promise.resolve(false);
133
+ const ev = this.opts.signAuth(this.challenge, this.url);
134
+ this.authed = this.publishAuth(ev);
135
+ return this.authed;
136
+ }
137
+ publishAuth(ev) {
138
+ return new Promise((resolve) => {
139
+ const timer = setTimeout(() => {
140
+ this.oks.delete(ev.id);
141
+ resolve(false);
142
+ }, this.timeout);
143
+ this.oks.set(ev.id, { resolve: (r) => resolve(r.ok), timer });
144
+ this.send(['AUTH', ev]);
145
+ }).then((ok) => {
146
+ if (!ok)
147
+ this.authed = null;
148
+ return ok;
149
+ });
150
+ }
151
+ onFrame(data) {
152
+ let msg;
153
+ try {
154
+ msg = JSON.parse(typeof data === 'string' ? data : String(data));
155
+ }
156
+ catch {
157
+ return;
158
+ }
159
+ if (!Array.isArray(msg) || typeof msg[0] !== 'string')
160
+ return;
161
+ const [verb, a, b, c] = msg;
162
+ switch (verb) {
163
+ case 'EVENT': {
164
+ const s = typeof a === 'string' ? this.subs.get(a) : undefined;
165
+ if (s && b && typeof b === 'object')
166
+ s.onEvent(b);
167
+ break;
168
+ }
169
+ case 'EOSE': {
170
+ if (typeof a === 'string')
171
+ this.subs.get(a)?.eose();
172
+ break;
173
+ }
174
+ case 'CLOSED': {
175
+ if (typeof a !== 'string')
176
+ break;
177
+ const s = this.subs.get(a);
178
+ if (!s)
179
+ break;
180
+ const why = typeof b === 'string' ? b : '';
181
+ if (why.startsWith('auth-required:') && !s.authRetried) {
182
+ s.authRetried = true;
183
+ void this.authenticate().then((ok) => {
184
+ if (ok && this.subs.has(a))
185
+ this.send(['REQ', a, ...s.filters]);
186
+ else
187
+ this.endSub(a, why);
188
+ });
189
+ }
190
+ else
191
+ this.endSub(a, why);
192
+ break;
193
+ }
194
+ case 'OK': {
195
+ const p = typeof a === 'string' ? this.oks.get(a) : undefined;
196
+ if (!p)
197
+ break;
198
+ clearTimeout(p.timer);
199
+ this.oks.delete(a);
200
+ p.resolve({ ok: b === true, message: typeof c === 'string' ? c : '' });
201
+ break;
202
+ }
203
+ case 'AUTH': {
204
+ if (typeof a === 'string') {
205
+ this.challenge = a;
206
+ this.authed = null;
207
+ // Answered up front when we can: a relay that requires AUTH refuses
208
+ // the first EVENT otherwise, and a live wrap refused is a wrap lost.
209
+ if (this.opts.signAuth)
210
+ void this.authenticate();
211
+ }
212
+ break;
213
+ }
214
+ case 'NOTICE': {
215
+ if (typeof a === 'string')
216
+ this.opts.onNotice?.(a);
217
+ break;
218
+ }
219
+ }
220
+ }
221
+ endSub(id, why) {
222
+ const s = this.subs.get(id);
223
+ if (!s)
224
+ return;
225
+ this.subs.delete(id);
226
+ s.closed(why);
227
+ }
228
+ }
229
+ /** A NIP-42 auth event for a relay's challenge, signed by the leaf's node key. */
230
+ export function authEvent(sign, challenge, relayUrl, now = Math.floor(Date.now() / 1000)) {
231
+ return sign(now, 22242, [['relay', relayUrl], ['challenge', challenge]], '');
232
+ }
package/dist/seal.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import * as didcomm from './didcomm.js;
2
+ import type { NostrEvent } from './event.js;
3
+ export declare const FRAGMENT_BYTES = 24000;
4
+ export declare const MAX_FRAGMENTS = 64;
5
+ export declare const ENVELOPE_MAX: number;
6
+ export declare const PARTIALS_PER_SENDER = 4;
7
+ export declare const PARTIALS_MAX = 64;
8
+ export declare const PARTIAL_TTL_SECONDS = 600;
9
+ export declare const EMPTY_TYPE = "https://didcomm.org/empty/1.0/empty";
10
+ export declare class SealError extends Error {
11
+ }
12
+ export interface LeafSecrets {
13
+ nodeSk: string;
14
+ agreementSk: Uint8Array;
15
+ }
16
+ export interface PeerKeys {
17
+ pubkey: string;
18
+ agreementPub: Uint8Array;
19
+ }
20
+ export interface Fragment {
21
+ frag: string;
22
+ i: number;
23
+ n: number;
24
+ data: string;
25
+ }
26
+ /** The JWE itself when it fits a wrap, else its pieces under one fragment id. */
27
+ export declare function fragments(jwe: didcomm.JWE): (didcomm.JWE | Fragment)[];
28
+ export interface SealOptions {
29
+ stored?: boolean;
30
+ now?: number;
31
+ }
32
+ /** Address, encrypt and wrap one message to a peer: the wraps to publish, in order. */
33
+ export declare function seal(message: Record<string, unknown>, me: LeafSecrets & {
34
+ pubkey: string;
35
+ }, to: PeerKeys, opts?: SealOptions): NostrEvent[];
36
+ export interface Opened {
37
+ message: Record<string, any>;
38
+ /** The x-only key of whoever sealed it. */
39
+ sender: string;
40
+ /** True for authcrypt: the agreement proved the sender. False for anoncrypt. */
41
+ authenticated: boolean;
42
+ wrapId: string;
43
+ }
44
+ /** Collects fragments by (sender, fragment id), bounded as the anchor bounds them. */
45
+ export declare class Reassembler {
46
+ private readonly partials;
47
+ /** The whole JWE once every fragment has arrived; null while waiting. */
48
+ add(frag: Fragment, sender: string, now: number): unknown | null;
49
+ }
50
+ /** Open one wrap addressed to this leaf. Null while a fragmented envelope is
51
+ * incomplete; throws with the reason for anything refused.
52
+ * resolveAgreement maps a sender's node key to its X25519 key (from its
53
+ * descriptor); a sender it cannot resolve cannot be authenticated. */
54
+ export declare function open(wrapEvent: NostrEvent, me: LeafSecrets & {
55
+ pubkey: string;
56
+ }, resolveAgreement: (pubkey: string) => Uint8Array | null | undefined, reassembler: Reassembler, now?: number): Opened | null;