@fabric-harness/channels 0.17.4 → 0.18.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -0
- package/dist/buzz-decisions.d.ts +174 -0
- package/dist/buzz-decisions.d.ts.map +1 -0
- package/dist/buzz-decisions.js +209 -0
- package/dist/buzz-decisions.js.map +1 -0
- package/dist/buzz-kinds.d.ts +34 -0
- package/dist/buzz-kinds.d.ts.map +1 -0
- package/dist/buzz-kinds.js +34 -0
- package/dist/buzz-kinds.js.map +1 -0
- package/dist/buzz-tail.d.ts +113 -0
- package/dist/buzz-tail.d.ts.map +1 -0
- package/dist/buzz-tail.js +305 -0
- package/dist/buzz-tail.js.map +1 -0
- package/dist/buzz.d.ts +166 -0
- package/dist/buzz.d.ts.map +1 -0
- package/dist/buzz.js +340 -0
- package/dist/buzz.js.map +1 -0
- package/dist/compatibility.d.ts +7 -0
- package/dist/compatibility.d.ts.map +1 -1
- package/dist/compatibility.js +1 -0
- package/dist/compatibility.js.map +1 -1
- package/package.json +15 -2
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { BuzzEvent } from './buzz.js';
|
|
2
|
+
/**
|
|
3
|
+
* `buzz-tail` — the durable WebSocket→route consumer for the Buzz channel
|
|
4
|
+
* (Fabric Buzz Collaboration Plan D15, B1-H).
|
|
5
|
+
*
|
|
6
|
+
* Buzz relays push events over Nostr NIP-01 WebSocket subscriptions rather
|
|
7
|
+
* than webhooks. `dedupeKey` downstream only deduplicates what was observed;
|
|
8
|
+
* it cannot prove every relay event was observed. This tail therefore:
|
|
9
|
+
*
|
|
10
|
+
* - keeps a **durable cursor** (max safely-forwarded `created_at`, persisted
|
|
11
|
+
* through the injected {@link BuzzCursorStore}; advanced only after a 2xx
|
|
12
|
+
* forward or a recorded dead-letter),
|
|
13
|
+
* - **backfills over HTTP** (`POST /query`) from `cursor - overlap` on every
|
|
14
|
+
* (re)start before going live, so outages longer than any reconnect window
|
|
15
|
+
* lose nothing (duplicates are collapsed downstream by event-id dedupe),
|
|
16
|
+
* - forwards **in order through one consumer queue** with retry
|
|
17
|
+
* classification: 408/429/5xx/network errors retry with bounded exponential
|
|
18
|
+
* backoff; other 4xx (and exhausted retries) are **dead-lettered** to the
|
|
19
|
+
* reconciliation hook and the cursor moves on,
|
|
20
|
+
* - handles **NIP-42** challenges including `OK` acknowledgement and re-`REQ`
|
|
21
|
+
* after auth or a `CLOSED` subscription,
|
|
22
|
+
* - shuts down cleanly: stops intake, drains the in-flight forward, persists
|
|
23
|
+
* the cursor, and closes the subscription.
|
|
24
|
+
*
|
|
25
|
+
* Runtime: needs a WebSocket implementation. Node ≥ 22 provides a global; on
|
|
26
|
+
* Node 20 pass `webSocketImpl` (e.g. from `undici` or `ws`).
|
|
27
|
+
*
|
|
28
|
+
* Buzz constraint (verified 2026-08-01): relay queries must specify `kinds` —
|
|
29
|
+
* an open-ended filter trips the relay's p-gate. Backfill and subscription
|
|
30
|
+
* always send an explicit kind list.
|
|
31
|
+
*/
|
|
32
|
+
type WebSocketLike = {
|
|
33
|
+
readonly readyState: number;
|
|
34
|
+
send(data: string): void;
|
|
35
|
+
close(): void;
|
|
36
|
+
addEventListener(type: string, listener: (event: {
|
|
37
|
+
data?: unknown;
|
|
38
|
+
code?: number;
|
|
39
|
+
}) => void): void;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Durable cursor persistence. Implementations must survive process restarts
|
|
43
|
+
* (file, database, durable object …). {@link inMemoryBuzzCursorStore} exists
|
|
44
|
+
* for tests and explicitly does NOT satisfy plan D15 in production.
|
|
45
|
+
*/
|
|
46
|
+
export interface BuzzCursorStore {
|
|
47
|
+
load(): Promise<number | undefined>;
|
|
48
|
+
save(cursorSeconds: number): Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
/** Test/development cursor store. Not durable — never use in production. */
|
|
51
|
+
export declare function inMemoryBuzzCursorStore(initial?: number): BuzzCursorStore & {
|
|
52
|
+
current(): number | undefined;
|
|
53
|
+
};
|
|
54
|
+
export type BuzzDeadLetterReason = 'permanent-status' | 'retries-exhausted' | 'unsigned-event';
|
|
55
|
+
export interface BuzzTailOptions {
|
|
56
|
+
/** Relay WebSocket URL, e.g. `ws://localhost:3000`. */
|
|
57
|
+
relayUrl: string;
|
|
58
|
+
/** Adapter identity secret key (64-char hex) — signs the NIP-42 AUTH event. */
|
|
59
|
+
secretKey: string;
|
|
60
|
+
/** Server-owned community/tenant forwarded in every envelope (plan D7). */
|
|
61
|
+
community: string;
|
|
62
|
+
/** Absolute URL of the Buzz channel's `/events` route. */
|
|
63
|
+
forwardUrl: string;
|
|
64
|
+
/** Shared secret for the forwarding envelope (must match the channel's). */
|
|
65
|
+
sharedSecret: string;
|
|
66
|
+
/** Durable cursor store (plan D15). Required — choose durability explicitly. */
|
|
67
|
+
cursorStore: BuzzCursorStore;
|
|
68
|
+
/**
|
|
69
|
+
* Channel ids to consume (NIP-29 `h` scope). Required: Buzz delivers live
|
|
70
|
+
* channel events only to `#h`-scoped subscriptions (verified live
|
|
71
|
+
* 2026-08-02 — an unscoped REQ receives stored events but no live fan-out),
|
|
72
|
+
* and scoping is also the membership-correct posture.
|
|
73
|
+
*/
|
|
74
|
+
channels: string[];
|
|
75
|
+
/** Kinds to subscribe to. Default: stream messages, forum posts/comments, reactions. */
|
|
76
|
+
kinds?: number[];
|
|
77
|
+
/** Backfill/subscription overlap window in seconds. Default 300. */
|
|
78
|
+
overlapSeconds?: number;
|
|
79
|
+
/** Backfill page size. Default 500. */
|
|
80
|
+
backfillLimit?: number;
|
|
81
|
+
/** Max forward attempts per event before dead-lettering. Default 8. */
|
|
82
|
+
maxAttempts?: number;
|
|
83
|
+
/** Retry delay per attempt (injectable for tests). Default bounded exponential. */
|
|
84
|
+
retryDelayMs?: (attempt: number) => number;
|
|
85
|
+
/** Reconnect backoff ceiling in milliseconds. Default 30_000. */
|
|
86
|
+
maxBackoffMs?: number;
|
|
87
|
+
/**
|
|
88
|
+
* NIP-11 connect-time enforcement (plan §5.5, B1-H item 3): NIPs the relay
|
|
89
|
+
* must advertise before the tail will consume from it. Default `[1, 42]`
|
|
90
|
+
* (base protocol + auth). Set to an empty array to disable — an explicit
|
|
91
|
+
* decision, never the default.
|
|
92
|
+
*/
|
|
93
|
+
requiredNips?: number[];
|
|
94
|
+
/** Reconciliation hook for events that could not be forwarded. */
|
|
95
|
+
onDeadLetter?: (event: BuzzEvent, reason: BuzzDeadLetterReason, status?: number) => void;
|
|
96
|
+
fetchImpl?: typeof fetch;
|
|
97
|
+
webSocketImpl?: new (url: string) => WebSocketLike;
|
|
98
|
+
now?: () => number;
|
|
99
|
+
onError?: (error: unknown) => void;
|
|
100
|
+
}
|
|
101
|
+
export interface BuzzTail {
|
|
102
|
+
/**
|
|
103
|
+
* Resolves once NIP-11 enforcement, the initial cursor load, and the HTTP
|
|
104
|
+
* backfill completed and the live socket is being established. Rejects when
|
|
105
|
+
* the relay fails NIP-11 enforcement — the tail refuses to consume.
|
|
106
|
+
*/
|
|
107
|
+
ready: Promise<void>;
|
|
108
|
+
close(): Promise<void>;
|
|
109
|
+
}
|
|
110
|
+
/** Start tailing a Buzz relay with durable, ordered, at-least-once forwarding. */
|
|
111
|
+
export declare function startBuzzTail(options: BuzzTailOptions): BuzzTail;
|
|
112
|
+
export {};
|
|
113
|
+
//# sourceMappingURL=buzz-tail.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buzz-tail.d.ts","sourceRoot":"","sources":["../src/buzz-tail.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,KAAK,aAAa,GAAG;IACnB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,KAAK,IAAI,IAAI,CAAC;IACd,gBA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EAAiE;IACjE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,kEAAkE;IAClE,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IACzF,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;IACzB,aAAa,CAAC,EAAE,KAAK,GAAG,EAAE,MAAM,KAAK,aAAa,CAAC;IACnD,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACpC;AAED,MAAM,WAAW,QAAQ;IACvB;;;;OAIG;IACH,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IACrB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAkBD,kFAAkF;AAClF,wBAAgB,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,QAAQ,CAwRhE"}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { hexToBytes } from '@fabric-harness/sdk/channel';
|
|
2
|
+
import { finalizeEvent } from 'nostr-tools/pure';
|
|
3
|
+
import { BUZZ_KINDS } from './buzz-kinds.js';
|
|
4
|
+
import { buzzHttpUrl, buzzNip98AuthHeader, probeBuzzRelay, signBuzzEnvelope } from './buzz.js';
|
|
5
|
+
/** Test/development cursor store. Not durable — never use in production. */
|
|
6
|
+
export function inMemoryBuzzCursorStore(initial) {
|
|
7
|
+
let value = initial;
|
|
8
|
+
return {
|
|
9
|
+
async load() {
|
|
10
|
+
return value;
|
|
11
|
+
},
|
|
12
|
+
async save(cursorSeconds) {
|
|
13
|
+
value = cursorSeconds;
|
|
14
|
+
},
|
|
15
|
+
current() {
|
|
16
|
+
return value;
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const DEFAULT_KINDS = [
|
|
21
|
+
BUZZ_KINDS.STREAM_MESSAGE,
|
|
22
|
+
BUZZ_KINDS.FORUM_POST,
|
|
23
|
+
BUZZ_KINDS.FORUM_COMMENT,
|
|
24
|
+
BUZZ_KINDS.REACTION,
|
|
25
|
+
];
|
|
26
|
+
function defaultRetryDelay(attempt) {
|
|
27
|
+
return Math.min(1_000 * 2 ** attempt, 60_000);
|
|
28
|
+
}
|
|
29
|
+
/** Retry classification: true → back off and retry; false → dead-letter now. */
|
|
30
|
+
function isRetryableStatus(status) {
|
|
31
|
+
return status === 408 || status === 429 || status >= 500;
|
|
32
|
+
}
|
|
33
|
+
/** Start tailing a Buzz relay with durable, ordered, at-least-once forwarding. */
|
|
34
|
+
export function startBuzzTail(options) {
|
|
35
|
+
const kinds = options.kinds ?? DEFAULT_KINDS;
|
|
36
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
37
|
+
const now = options.now ?? (() => Date.now());
|
|
38
|
+
const overlap = options.overlapSeconds ?? 300;
|
|
39
|
+
const backfillLimit = options.backfillLimit ?? 500;
|
|
40
|
+
const maxAttempts = options.maxAttempts ?? 8;
|
|
41
|
+
const retryDelay = options.retryDelayMs ?? defaultRetryDelay;
|
|
42
|
+
const maxBackoff = options.maxBackoffMs ?? 30_000;
|
|
43
|
+
const report = options.onError ?? (() => { });
|
|
44
|
+
const deadLetter = options.onDeadLetter ?? (() => { });
|
|
45
|
+
const WebSocketImpl = options.webSocketImpl ??
|
|
46
|
+
globalThis.WebSocket;
|
|
47
|
+
if (!WebSocketImpl) {
|
|
48
|
+
throw new Error('No WebSocket implementation available: use Node >= 22 or pass webSocketImpl.');
|
|
49
|
+
}
|
|
50
|
+
const WebSocketCtor = WebSocketImpl;
|
|
51
|
+
const subscriptionId = 'fabric-buzz-tail';
|
|
52
|
+
const queryUrl = `${buzzHttpUrl(options.relayUrl)}/query`;
|
|
53
|
+
let closed = false;
|
|
54
|
+
let socket;
|
|
55
|
+
let backoff = 1_000;
|
|
56
|
+
let reconnectTimer;
|
|
57
|
+
/** Highest safely-consumed created_at (forwarded 2xx or dead-lettered). */
|
|
58
|
+
let cursor;
|
|
59
|
+
const queue = [];
|
|
60
|
+
let draining = Promise.resolve();
|
|
61
|
+
let drainActive = false;
|
|
62
|
+
function sleep(ms) {
|
|
63
|
+
return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));
|
|
64
|
+
}
|
|
65
|
+
async function forwardOnce(event) {
|
|
66
|
+
const body = JSON.stringify({ community: options.community, relayUrl: options.relayUrl, event });
|
|
67
|
+
const timestampSeconds = Math.floor(now() / 1000);
|
|
68
|
+
const signature = await signBuzzEnvelope(options.sharedSecret, timestampSeconds, body);
|
|
69
|
+
return fetchImpl(options.forwardUrl, {
|
|
70
|
+
method: 'POST',
|
|
71
|
+
headers: {
|
|
72
|
+
'content-type': 'application/json',
|
|
73
|
+
'x-fabric-timestamp': String(timestampSeconds),
|
|
74
|
+
'x-fabric-signature': signature,
|
|
75
|
+
},
|
|
76
|
+
body,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
async function consume(event) {
|
|
80
|
+
if (typeof event.sig !== 'string' || event.sig.length === 0) {
|
|
81
|
+
// The route requires an author signature; a sig-stripped read surface
|
|
82
|
+
// cannot be verified and must be reconciled, not silently dropped.
|
|
83
|
+
deadLetter(event, 'unsigned-event');
|
|
84
|
+
advanceCursor(event);
|
|
85
|
+
await persistCursor();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
for (let attempt = 0;; attempt += 1) {
|
|
89
|
+
let status;
|
|
90
|
+
try {
|
|
91
|
+
const response = await forwardOnce(event);
|
|
92
|
+
status = response.status;
|
|
93
|
+
if (response.status >= 200 && response.status < 300) {
|
|
94
|
+
advanceCursor(event);
|
|
95
|
+
await persistCursor();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (!isRetryableStatus(response.status)) {
|
|
99
|
+
deadLetter(event, 'permanent-status', response.status);
|
|
100
|
+
advanceCursor(event);
|
|
101
|
+
await persistCursor();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
report(error); // network failure — retryable
|
|
107
|
+
}
|
|
108
|
+
if (closed || attempt + 1 >= maxAttempts) {
|
|
109
|
+
deadLetter(event, 'retries-exhausted', status);
|
|
110
|
+
advanceCursor(event);
|
|
111
|
+
await persistCursor();
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
await sleep(retryDelay(attempt));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function advanceCursor(event) {
|
|
118
|
+
if (typeof event.created_at === 'number') {
|
|
119
|
+
cursor = cursor === undefined ? event.created_at : Math.max(cursor, event.created_at);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async function persistCursor() {
|
|
123
|
+
if (cursor !== undefined) {
|
|
124
|
+
try {
|
|
125
|
+
await options.cursorStore.save(cursor);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
report(error);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function enqueue(event) {
|
|
133
|
+
queue.push(event);
|
|
134
|
+
if (!drainActive) {
|
|
135
|
+
drainActive = true;
|
|
136
|
+
draining = (async () => {
|
|
137
|
+
while (queue.length > 0 && !closed) {
|
|
138
|
+
const next = queue.shift();
|
|
139
|
+
if (next)
|
|
140
|
+
await consume(next);
|
|
141
|
+
}
|
|
142
|
+
// Drain any remainder even when closing so in-flight work finishes.
|
|
143
|
+
while (queue.length > 0) {
|
|
144
|
+
const next = queue.shift();
|
|
145
|
+
if (next)
|
|
146
|
+
await consume(next);
|
|
147
|
+
}
|
|
148
|
+
drainActive = false;
|
|
149
|
+
})();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function sinceSeconds() {
|
|
153
|
+
const base = cursor ?? Math.floor(now() / 1000);
|
|
154
|
+
return Math.max(0, base - overlap);
|
|
155
|
+
}
|
|
156
|
+
function filter(since, limit) {
|
|
157
|
+
return { kinds, '#h': options.channels, since, ...(limit !== undefined ? { limit } : {}) };
|
|
158
|
+
}
|
|
159
|
+
/** HTTP backfill (plan D15): page forward from the cursor until drained. */
|
|
160
|
+
async function backfill() {
|
|
161
|
+
let since = sinceSeconds();
|
|
162
|
+
for (;;) {
|
|
163
|
+
let events;
|
|
164
|
+
try {
|
|
165
|
+
// The bridge expects a SEQUENCE of filters (verified live 2026-08-02).
|
|
166
|
+
const body = JSON.stringify([filter(since, backfillLimit)]);
|
|
167
|
+
const response = await fetchImpl(queryUrl, {
|
|
168
|
+
method: 'POST',
|
|
169
|
+
headers: {
|
|
170
|
+
'content-type': 'application/json',
|
|
171
|
+
// The bridge requires NIP-98 auth on reads as well as writes.
|
|
172
|
+
authorization: await buzzNip98AuthHeader(options.secretKey, queryUrl, 'POST', body, now),
|
|
173
|
+
},
|
|
174
|
+
body,
|
|
175
|
+
});
|
|
176
|
+
if (!response.ok) {
|
|
177
|
+
report(new Error(`backfill query failed: ${response.status}`));
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
events = (await response.json());
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
report(error);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (!Array.isArray(events) || events.length === 0)
|
|
187
|
+
return;
|
|
188
|
+
const ordered = [...events].sort((a, b) => a.created_at - b.created_at);
|
|
189
|
+
for (const event of ordered)
|
|
190
|
+
enqueue(event);
|
|
191
|
+
await draining;
|
|
192
|
+
const maxSeen = ordered[ordered.length - 1]?.created_at ?? since;
|
|
193
|
+
if (events.length < backfillLimit || maxSeen <= since)
|
|
194
|
+
return; // drained or no progress
|
|
195
|
+
since = maxSeen;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function subscribe(ws) {
|
|
199
|
+
ws.send(JSON.stringify(['REQ', subscriptionId, filter(sinceSeconds())]));
|
|
200
|
+
}
|
|
201
|
+
function connect() {
|
|
202
|
+
if (closed)
|
|
203
|
+
return;
|
|
204
|
+
const ws = new WebSocketCtor(options.relayUrl);
|
|
205
|
+
socket = ws;
|
|
206
|
+
ws.addEventListener('open', () => {
|
|
207
|
+
backoff = 1_000;
|
|
208
|
+
subscribe(ws);
|
|
209
|
+
});
|
|
210
|
+
ws.addEventListener('message', (messageEvent) => {
|
|
211
|
+
void (async () => {
|
|
212
|
+
try {
|
|
213
|
+
const frame = JSON.parse(String(messageEvent.data));
|
|
214
|
+
const [verb] = frame;
|
|
215
|
+
if (verb === 'AUTH' && typeof frame[1] === 'string') {
|
|
216
|
+
const auth = finalizeEvent({
|
|
217
|
+
kind: BUZZ_KINDS.AUTH,
|
|
218
|
+
created_at: Math.floor(now() / 1000),
|
|
219
|
+
tags: [
|
|
220
|
+
['relay', options.relayUrl],
|
|
221
|
+
['challenge', frame[1]],
|
|
222
|
+
],
|
|
223
|
+
content: '',
|
|
224
|
+
}, hexToBytes(options.secretKey));
|
|
225
|
+
ws.send(JSON.stringify(['AUTH', auth]));
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (verb === 'OK' && frame[2] === true) {
|
|
229
|
+
// NIP-42 acknowledgement — the pre-auth REQ may have been
|
|
230
|
+
// rejected, so re-subscribe under the authenticated session.
|
|
231
|
+
subscribe(ws);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (verb === 'CLOSED' && frame[1] === subscriptionId) {
|
|
235
|
+
// Subscription closed server-side (e.g. auth-required raced the
|
|
236
|
+
// REQ). AUTH flow re-subscribes via OK; otherwise retry directly.
|
|
237
|
+
const reason = typeof frame[2] === 'string' ? frame[2] : '';
|
|
238
|
+
if (!reason.includes('auth'))
|
|
239
|
+
subscribe(ws);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (verb === 'EVENT' && frame[1] === subscriptionId && frame[2] && typeof frame[2] === 'object') {
|
|
243
|
+
enqueue(frame[2]);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
report(error);
|
|
248
|
+
}
|
|
249
|
+
})();
|
|
250
|
+
});
|
|
251
|
+
ws.addEventListener('close', () => {
|
|
252
|
+
if (closed)
|
|
253
|
+
return;
|
|
254
|
+
reconnectTimer = setTimeout(() => {
|
|
255
|
+
// A reconnect is a restart for delivery purposes: backfill the gap
|
|
256
|
+
// over HTTP before (re)subscribing live.
|
|
257
|
+
void backfill().finally(connect);
|
|
258
|
+
}, backoff);
|
|
259
|
+
backoff = Math.min(backoff * 2, maxBackoff);
|
|
260
|
+
});
|
|
261
|
+
ws.addEventListener('error', (event) => {
|
|
262
|
+
report(event);
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
const requiredNips = options.requiredNips ?? [1, 42];
|
|
266
|
+
const ready = (async () => {
|
|
267
|
+
if (requiredNips.length > 0) {
|
|
268
|
+
// Feature-detect, never assume (plan §5.5). A relay that does not
|
|
269
|
+
// advertise the required NIPs is refused outright.
|
|
270
|
+
const info = await probeBuzzRelay(options.relayUrl, fetchImpl);
|
|
271
|
+
const advertised = new Set(info.supported_nips ?? []);
|
|
272
|
+
const missing = requiredNips.filter((nip) => !advertised.has(nip));
|
|
273
|
+
if (missing.length > 0) {
|
|
274
|
+
closed = true;
|
|
275
|
+
throw new Error(`relay ${options.relayUrl} does not advertise required NIPs: ${missing.join(', ')}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
try {
|
|
279
|
+
cursor = await options.cursorStore.load();
|
|
280
|
+
}
|
|
281
|
+
catch (error) {
|
|
282
|
+
report(error);
|
|
283
|
+
}
|
|
284
|
+
await backfill();
|
|
285
|
+
connect();
|
|
286
|
+
})();
|
|
287
|
+
return {
|
|
288
|
+
ready,
|
|
289
|
+
async close() {
|
|
290
|
+
closed = true;
|
|
291
|
+
if (reconnectTimer)
|
|
292
|
+
clearTimeout(reconnectTimer);
|
|
293
|
+
try {
|
|
294
|
+
socket?.send(JSON.stringify(['CLOSE', subscriptionId]));
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
// socket may already be gone; closing is best-effort
|
|
298
|
+
}
|
|
299
|
+
socket?.close();
|
|
300
|
+
await draining;
|
|
301
|
+
await persistCursor();
|
|
302
|
+
},
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
//# sourceMappingURL=buzz-tail.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buzz-tail.js","sourceRoot":"","sources":["../src/buzz-tail.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAmD/F,4EAA4E;AAC5E,MAAM,UAAU,uBAAuB,CAAC,OAAgB;IACtD,IAAI,KAAK,GAAG,OAAO,CAAC;IACpB,OAAO;QACL,KAAK,CAAC,IAAI;YACR,OAAO,KAAK,CAAC;QACf,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,aAAqB;YAC9B,KAAK,GAAG,aAAa,CAAC;QACxB,CAAC;QACD,OAAO;YACL,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;AACJ,CAAC;AA6DD,MAAM,aAAa,GAAG;IACpB,UAAU,CAAC,cAAc;IACzB,UAAU,CAAC,UAAU;IACrB,UAAU,CAAC,aAAa;IACxB,UAAU,CAAC,QAAQ;CACpB,CAAC;AAEF,SAAS,iBAAiB,CAAC,OAAe;IACxC,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,IAAI,OAAO,EAAE,MAAM,CAAC,CAAC;AAChD,CAAC;AAED,gFAAgF;AAChF,SAAS,iBAAiB,CAAC,MAAc;IACvC,OAA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
|
package/dist/buzz.d.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import type { Channel, ToolDef } from '@fabric-harness/sdk/channel';
|
|
2
|
+
import type { BuzzCardReceiptStore } from './buzz-decisions.js';
|
|
3
|
+
/**
|
|
4
|
+
* Buzz channel — event ingress from a Buzz relay (block/buzz) and outbound
|
|
5
|
+
* posting tools.
|
|
6
|
+
*
|
|
7
|
+
* Buzz pushes over WebSocket (Nostr NIP-01), not webhooks, so ingress arrives
|
|
8
|
+
* via the `buzz-tail` transport shim (`./buzz-tail`), which holds a NIP-42
|
|
9
|
+
* authenticated subscription and forwards each event to this channel's
|
|
10
|
+
* `/events` route inside an `X-Fabric-Signature: v1=` HMAC envelope. A future
|
|
11
|
+
* Buzz workflow `call_webhook` egress can target the same route — one
|
|
12
|
+
* normalizer, two transports.
|
|
13
|
+
*
|
|
14
|
+
* Governance boundaries (Fabric Buzz Collaboration Plan D7/D11): this adapter
|
|
15
|
+
* performs no authorization and never talks to Temporal. It stamps the Nostr
|
|
16
|
+
* pubkey as the acting `actor` (candidate identity); binding resolution and
|
|
17
|
+
* capability checks happen in the vertical's governed decision-ingress action.
|
|
18
|
+
* Stock Buzz Desktop reactions omit the NIP-29 channel tag, so the adapter may
|
|
19
|
+
* derive that transport scope from one exact, persisted decision-card receipt;
|
|
20
|
+
* the receipt grants no decision authority.
|
|
21
|
+
*/
|
|
22
|
+
/** Nostr event shape (NIP-01). Kept local so the handler path stays SDK-only. */
|
|
23
|
+
export interface BuzzEvent {
|
|
24
|
+
id: string;
|
|
25
|
+
pubkey: string;
|
|
26
|
+
created_at: number;
|
|
27
|
+
kind: number;
|
|
28
|
+
tags: string[][];
|
|
29
|
+
content: string;
|
|
30
|
+
sig: string;
|
|
31
|
+
}
|
|
32
|
+
export interface BuzzEnvelope {
|
|
33
|
+
/** Community identifier (relay-host-derived tenant boundary). */
|
|
34
|
+
community?: string;
|
|
35
|
+
/** Source relay URL (informational). */
|
|
36
|
+
relayUrl?: string;
|
|
37
|
+
event?: BuzzEvent;
|
|
38
|
+
}
|
|
39
|
+
export interface BuzzThreadRef {
|
|
40
|
+
community: string;
|
|
41
|
+
channelId: string;
|
|
42
|
+
rootEventId: string;
|
|
43
|
+
}
|
|
44
|
+
export interface BuzzChannelOptions {
|
|
45
|
+
/** Persistent agent that inbound Buzz events dispatch to. */
|
|
46
|
+
agent: string;
|
|
47
|
+
/** Shared secret for the tail→route envelope (`X-Fabric-Signature: v1=`). */
|
|
48
|
+
sharedSecret: string;
|
|
49
|
+
/**
|
|
50
|
+
* The adapter identity's public key (64-char hex). Events authored by this
|
|
51
|
+
* key are ignored (loop suppression). Derive with `buzzPublicKey(secretKey)`.
|
|
52
|
+
*/
|
|
53
|
+
selfPubkey: string;
|
|
54
|
+
/**
|
|
55
|
+
* Server-owned tenant for this relay deployment (plan D7). The Fabric
|
|
56
|
+
* tenant is configuration, never taken from the event or envelope; an
|
|
57
|
+
* envelope claiming a different community is refused with 403.
|
|
58
|
+
*/
|
|
59
|
+
community: string;
|
|
60
|
+
/**
|
|
61
|
+
* Server-owned channel allowlist for this deployment. When present,
|
|
62
|
+
* channel-tagged events outside this list are ignored. This list is also
|
|
63
|
+
* required for receipt-aware correlation of stock Buzz Desktop reactions,
|
|
64
|
+
* whose NIP-25 events carry an `e` target but no `h` channel tag.
|
|
65
|
+
*/
|
|
66
|
+
channels?: readonly string[];
|
|
67
|
+
/**
|
|
68
|
+
* Durable decision-card receipt lookup. When this and `channels` are set, an
|
|
69
|
+
* `h`-less reaction is admitted only if its sole `e` target exactly matches
|
|
70
|
+
* one receipt in one configured channel. The channel is derived from that
|
|
71
|
+
* receipt; the adapter still performs no identity or decision authorization.
|
|
72
|
+
*/
|
|
73
|
+
decisionReceiptStore?: Pick<BuzzCardReceiptStore, 'findByCardEvent'>;
|
|
74
|
+
/** Max clock skew (seconds) tolerated on the envelope timestamp. Default 300. */
|
|
75
|
+
maxSkewSeconds?: number;
|
|
76
|
+
/** Clock injection for tests. */
|
|
77
|
+
now?: () => number;
|
|
78
|
+
}
|
|
79
|
+
export interface BuzzChannel extends Channel {
|
|
80
|
+
conversationKey(ref: BuzzThreadRef): string;
|
|
81
|
+
parseConversationKey(id: string): BuzzThreadRef;
|
|
82
|
+
}
|
|
83
|
+
/** Derive the adapter identity's public key from its secret key (64-char hex). */
|
|
84
|
+
export declare function buzzPublicKey(secretKeyHex: string): string;
|
|
85
|
+
/** Serialize a Buzz thread into the stable instance id used by `createBuzzChannel`. */
|
|
86
|
+
export declare function buzzConversationKey(ref: BuzzThreadRef): string;
|
|
87
|
+
/** Parse a Buzz instance id back into the thread ref. */
|
|
88
|
+
export declare function parseBuzzConversationKey(id: string): BuzzThreadRef;
|
|
89
|
+
/** Family signed-envelope standard: `v1=hex(hmac-sha256(secret, "<ts>.<body>"))`. */
|
|
90
|
+
export declare function signBuzzEnvelope(secret: string, timestampSeconds: number, rawBody: string): Promise<string>;
|
|
91
|
+
/**
|
|
92
|
+
* Buzz events channel. Verifies the tail envelope HMAC (timestamped, replay
|
|
93
|
+
* bounded), verifies the inner event's Schnorr signature, normalizes stream
|
|
94
|
+
* messages / forum posts / reactions, and dispatches to a persistent agent
|
|
95
|
+
* keyed by (community, channel, thread root) — with the Nostr event id as the
|
|
96
|
+
* dedupe key (exactly-once), the community as tenant, and the author pubkey as
|
|
97
|
+
* the acting `actor`.
|
|
98
|
+
*/
|
|
99
|
+
export declare function createBuzzChannel(options: BuzzChannelOptions): BuzzChannel;
|
|
100
|
+
/** Convert a relay WebSocket URL to its HTTP origin (Buzz serves both on one port). */
|
|
101
|
+
export declare function buzzHttpUrl(relayUrl: string): string;
|
|
102
|
+
export interface BuzzPostConfig {
|
|
103
|
+
/** Relay URL (`ws://` or `http://` form both accepted). */
|
|
104
|
+
relayUrl: string;
|
|
105
|
+
/** Adapter identity secret key (64-char hex). */
|
|
106
|
+
secretKey: string;
|
|
107
|
+
fetchImpl?: typeof fetch;
|
|
108
|
+
/** Clock injection for tests (event `created_at`). */
|
|
109
|
+
now?: () => number;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Build the `Authorization: Nostr <base64(kind-27235)>` header for a Buzz
|
|
113
|
+
* HTTP-bridge request. Includes the `payload` sha256 tag when a body is given
|
|
114
|
+
* (NIP-98 SHOULD for POST; Buzz verifies it when present). Each call mints a
|
|
115
|
+
* fresh single-use event — the relay replay-guards by event id.
|
|
116
|
+
*/
|
|
117
|
+
export declare function buzzNip98AuthHeader(secretKeyHex: string, url: string, method: string, bodyText?: string, now?: () => number): Promise<string>;
|
|
118
|
+
export interface BuzzPostResult {
|
|
119
|
+
event_id?: string;
|
|
120
|
+
accepted?: boolean;
|
|
121
|
+
message?: string;
|
|
122
|
+
}
|
|
123
|
+
/** Sign a Buzz event with the adapter identity and submit it over the relay HTTP bridge. */
|
|
124
|
+
export declare function postSignedBuzzEvent(config: BuzzPostConfig, template: {
|
|
125
|
+
kind: number;
|
|
126
|
+
content: string;
|
|
127
|
+
tags: string[][];
|
|
128
|
+
}): Promise<BuzzPostResult>;
|
|
129
|
+
/** Outbound tool: post a message in the Buzz channel this agent is handling. */
|
|
130
|
+
export declare function postInBuzzChannel(ref: BuzzThreadRef, config: BuzzPostConfig): ToolDef<{
|
|
131
|
+
text: string;
|
|
132
|
+
}, BuzzPostResult>;
|
|
133
|
+
/** Outbound tool: reply in the Buzz thread this agent is handling. */
|
|
134
|
+
export declare function replyInBuzzThread(ref: BuzzThreadRef, config: BuzzPostConfig): ToolDef<{
|
|
135
|
+
text: string;
|
|
136
|
+
}, BuzzPostResult>;
|
|
137
|
+
/** Outbound tool: add an emoji reaction to an event in the handled channel. */
|
|
138
|
+
export declare function addBuzzReaction(ref: BuzzThreadRef, config: BuzzPostConfig): ToolDef<{
|
|
139
|
+
emoji: string;
|
|
140
|
+
targetEventId: string;
|
|
141
|
+
}, BuzzPostResult>;
|
|
142
|
+
/**
|
|
143
|
+
* Outbound tool: post a decision-request card.
|
|
144
|
+
*
|
|
145
|
+
* @deprecated Use `postBuzzDecisionCard` from `@fabric-harness/channels/buzz-decisions`
|
|
146
|
+
* — it renders the canonical card AND stores the card receipt the
|
|
147
|
+
* deterministic bridge requires (plan D14). This tool posts a tagged card but
|
|
148
|
+
* records no receipt, so reactions on it cannot resolve to a decision.
|
|
149
|
+
*/
|
|
150
|
+
export declare function postBuzzDecisionRequest(ref: BuzzThreadRef, config: BuzzPostConfig): ToolDef<{
|
|
151
|
+
approvalRequestId: string;
|
|
152
|
+
title: string;
|
|
153
|
+
body: string;
|
|
154
|
+
options?: string[];
|
|
155
|
+
}, BuzzPostResult>;
|
|
156
|
+
/** NIP-11 relay information document (feature detection — plan §5.5). */
|
|
157
|
+
export interface BuzzRelayInfo {
|
|
158
|
+
name?: string;
|
|
159
|
+
supported_nips?: number[];
|
|
160
|
+
supported_extensions?: string[];
|
|
161
|
+
limitation?: Record<string, unknown>;
|
|
162
|
+
[key: string]: unknown;
|
|
163
|
+
}
|
|
164
|
+
/** Probe a Buzz relay's NIP-11 document. Detect features; never assume them. */
|
|
165
|
+
export declare function probeBuzzRelay(relayUrl: string, fetchImpl?: typeof fetch): Promise<BuzzRelayInfo>;
|
|
166
|
+
//# sourceMappingURL=buzz.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buzz.d.ts","sourceRoot":"","sources":["../src/buzz.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,OAAO,EAAkB,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAEpF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAGhE;;;;;;;;;;;;;;;;;;GAkBG;AAEH,iFAAiF;AACjF,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC;IACjB,OAA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