@941design/marmot 0.0.0-stage → 0.2.0-alpha.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 (192) hide show
  1. package/CHANGELOG.md +709 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +127 -0
  25. package/dist/account/teardown.js +856 -0
  26. package/dist/client/before-create-group.d.ts +18 -0
  27. package/dist/client/before-create-group.js +65 -0
  28. package/dist/client/before-publish-hooks.d.ts +121 -0
  29. package/dist/client/before-publish-hooks.js +180 -0
  30. package/dist/client/client-config.d.ts +42 -0
  31. package/dist/client/client-config.js +13 -0
  32. package/dist/client/commit-redrive.d.ts +68 -0
  33. package/dist/client/commit-redrive.js +221 -0
  34. package/dist/client/component-update.d.ts +43 -0
  35. package/dist/client/component-update.js +53 -0
  36. package/dist/client/confirm-hooks.d.ts +50 -0
  37. package/dist/client/confirm-hooks.js +59 -0
  38. package/dist/client/create-client.d.ts +1022 -0
  39. package/dist/client/create-client.js +1125 -0
  40. package/dist/client/group-disband.d.ts +28 -0
  41. package/dist/client/group-disband.js +64 -0
  42. package/dist/client/group-history.d.ts +435 -0
  43. package/dist/client/group-history.js +1295 -0
  44. package/dist/client/group-profile.d.ts +31 -0
  45. package/dist/client/group-profile.js +62 -0
  46. package/dist/client/group-records.d.ts +485 -0
  47. package/dist/client/group-records.js +1034 -0
  48. package/dist/client/group-removal.d.ts +36 -0
  49. package/dist/client/group-removal.js +127 -0
  50. package/dist/client/group-remove-member.d.ts +49 -0
  51. package/dist/client/group-remove-member.js +163 -0
  52. package/dist/client/group-runtime.d.ts +388 -0
  53. package/dist/client/group-runtime.js +2701 -0
  54. package/dist/client/group-snapshot.d.ts +98 -0
  55. package/dist/client/group-snapshot.js +453 -0
  56. package/dist/client/history-pages.d.ts +107 -0
  57. package/dist/client/history-pages.js +194 -0
  58. package/dist/client/inbox-send.d.ts +19 -0
  59. package/dist/client/inbox-send.js +71 -0
  60. package/dist/client/index.d.ts +21 -0
  61. package/dist/client/index.js +13 -0
  62. package/dist/client/ingest.d.ts +82 -0
  63. package/dist/client/ingest.js +1550 -0
  64. package/dist/client/lifecycle-events.d.ts +63 -0
  65. package/dist/client/lifecycle-events.js +35 -0
  66. package/dist/client/opaque-candidates.d.ts +81 -0
  67. package/dist/client/opaque-candidates.js +169 -0
  68. package/dist/client/own-change-outbox.d.ts +66 -0
  69. package/dist/client/own-change-outbox.js +156 -0
  70. package/dist/client/pending-leaf.d.ts +116 -0
  71. package/dist/client/pending-leaf.js +378 -0
  72. package/dist/client/permissions.d.ts +9 -0
  73. package/dist/client/permissions.js +12 -0
  74. package/dist/client/pipeline.d.ts +554 -0
  75. package/dist/client/pipeline.js +3545 -0
  76. package/dist/client/reentrancy-guard.d.ts +96 -0
  77. package/dist/client/reentrancy-guard.js +153 -0
  78. package/dist/client/rekey.d.ts +58 -0
  79. package/dist/client/rekey.js +149 -0
  80. package/dist/client/transport-policy.d.ts +181 -0
  81. package/dist/client/transport-policy.js +214 -0
  82. package/dist/history/equivocation.d.ts +55 -0
  83. package/dist/history/equivocation.js +113 -0
  84. package/dist/history/fencing.d.ts +25 -0
  85. package/dist/history/fencing.js +61 -0
  86. package/dist/history/hex.d.ts +3 -0
  87. package/dist/history/hex.js +10 -0
  88. package/dist/history/index.d.ts +73 -0
  89. package/dist/history/index.js +31 -0
  90. package/dist/history/notifications.d.ts +270 -0
  91. package/dist/history/notifications.js +264 -0
  92. package/dist/history/ordering-key.d.ts +24 -0
  93. package/dist/history/ordering-key.js +101 -0
  94. package/dist/history/own-change-fork.d.ts +112 -0
  95. package/dist/history/own-change-fork.js +196 -0
  96. package/dist/history/own-change.d.ts +106 -0
  97. package/dist/history/own-change.js +146 -0
  98. package/dist/history/policy.d.ts +48 -0
  99. package/dist/history/policy.js +52 -0
  100. package/dist/history/retained-window.d.ts +215 -0
  101. package/dist/history/retained-window.js +565 -0
  102. package/dist/inbox/demux.d.ts +90 -0
  103. package/dist/inbox/demux.js +78 -0
  104. package/dist/inbox/handler-registry.d.ts +42 -0
  105. package/dist/inbox/handler-registry.js +37 -0
  106. package/dist/inbox/index.d.ts +11 -0
  107. package/dist/inbox/index.js +10 -0
  108. package/dist/inbox/seen-set.d.ts +82 -0
  109. package/dist/inbox/seen-set.js +202 -0
  110. package/dist/inbox/subscription.d.ts +236 -0
  111. package/dist/inbox/subscription.js +644 -0
  112. package/dist/index.d.ts +10 -0
  113. package/dist/index.js +9 -0
  114. package/dist/invitations/competing-welcome.d.ts +223 -0
  115. package/dist/invitations/competing-welcome.js +128 -0
  116. package/dist/invitations/decline.d.ts +61 -0
  117. package/dist/invitations/decline.js +143 -0
  118. package/dist/invitations/expect-welcome.d.ts +66 -0
  119. package/dist/invitations/expect-welcome.js +138 -0
  120. package/dist/invitations/index.d.ts +16 -0
  121. package/dist/invitations/index.js +16 -0
  122. package/dist/invitations/invite.d.ts +303 -0
  123. package/dist/invitations/invite.js +966 -0
  124. package/dist/invitations/offers.d.ts +79 -0
  125. package/dist/invitations/offers.js +115 -0
  126. package/dist/invitations/on-proposal.d.ts +47 -0
  127. package/dist/invitations/on-proposal.js +40 -0
  128. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  129. package/dist/invitations/pending-proposal-policy.js +139 -0
  130. package/dist/invitations/proposal-deadline.d.ts +133 -0
  131. package/dist/invitations/proposal-deadline.js +164 -0
  132. package/dist/invitations/relay-planes.d.ts +43 -0
  133. package/dist/invitations/relay-planes.js +70 -0
  134. package/dist/invitations/welcome-processor.d.ts +253 -0
  135. package/dist/invitations/welcome-processor.js +1180 -0
  136. package/dist/key-packages/device-key.d.ts +131 -0
  137. package/dist/key-packages/device-key.js +272 -0
  138. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  139. package/dist/key-packages/device-rotation-records.js +173 -0
  140. package/dist/key-packages/group-refs.d.ts +40 -0
  141. package/dist/key-packages/group-refs.js +79 -0
  142. package/dist/key-packages/index.d.ts +18 -0
  143. package/dist/key-packages/index.js +18 -0
  144. package/dist/key-packages/key-package-ref.d.ts +16 -0
  145. package/dist/key-packages/key-package-ref.js +21 -0
  146. package/dist/key-packages/observation-stream.d.ts +4 -0
  147. package/dist/key-packages/observation-stream.js +120 -0
  148. package/dist/key-packages/offer-rumor.d.ts +26 -0
  149. package/dist/key-packages/offer-rumor.js +69 -0
  150. package/dist/key-packages/publisher.d.ts +174 -0
  151. package/dist/key-packages/publisher.js +1247 -0
  152. package/dist/key-packages/select-key-package.d.ts +24 -0
  153. package/dist/key-packages/select-key-package.js +90 -0
  154. package/dist/key-packages/slot-manager.d.ts +167 -0
  155. package/dist/key-packages/slot-manager.js +327 -0
  156. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  157. package/dist/key-packages/validate-key-package-event.js +49 -0
  158. package/dist/media/cache.d.ts +14 -0
  159. package/dist/media/cache.js +10 -0
  160. package/dist/media/index.d.ts +52 -0
  161. package/dist/media/index.js +71 -0
  162. package/dist/mls.d.ts +15 -0
  163. package/dist/mls.js +15 -0
  164. package/dist/shared/account-pubkey.d.ts +4 -0
  165. package/dist/shared/account-pubkey.js +10 -0
  166. package/dist/shared/errors.d.ts +21 -0
  167. package/dist/shared/errors.js +85 -0
  168. package/dist/shared/hex.d.ts +4 -0
  169. package/dist/shared/hex.js +13 -0
  170. package/dist/shared/index.d.ts +14 -0
  171. package/dist/shared/index.js +14 -0
  172. package/dist/shared/kinds.d.ts +8 -0
  173. package/dist/shared/kinds.js +28 -0
  174. package/dist/shared/publish-classification.d.ts +26 -0
  175. package/dist/shared/publish-classification.js +31 -0
  176. package/dist/storage/envelope.d.ts +39 -0
  177. package/dist/storage/envelope.js +201 -0
  178. package/dist/storage/index.d.ts +227 -0
  179. package/dist/storage/index.js +459 -0
  180. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  181. package/dist/storage/indexeddb/idb-types.js +1 -0
  182. package/dist/storage/indexeddb/index.d.ts +17 -0
  183. package/dist/storage/indexeddb/index.js +141 -0
  184. package/dist/storage/lease.d.ts +41 -0
  185. package/dist/storage/lease.js +117 -0
  186. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  187. package/dist/storage/memory/deterministic-signer.js +65 -0
  188. package/dist/storage/memory/index.d.ts +32 -0
  189. package/dist/storage/memory/index.js +87 -0
  190. package/dist/storage/memory/lock-manager.d.ts +8 -0
  191. package/dist/storage/memory/lock-manager.js +71 -0
  192. package/package.json +66 -3
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Paginated history fetch over the narrowed `TransportContract`'s
3
+ * `requestWithDeadline` — reusable by every history reader (kind-445 group
4
+ * sync; inbox and history backfills).
5
+ *
6
+ * Relays cap each response server-side (a `max_limit`, commonly ~500,
7
+ * newest first) whatever `limit` the REQ asks for, so one request over a
8
+ * backlog larger than that cap silently returns only its newest part.
9
+ * `fetchHistoryPages` therefore walks EACH relay backwards on its own
10
+ * (a merged multi-relay response cannot say which relay truncated where):
11
+ *
12
+ * 1. page 1 asks `{...filter, limit}`;
13
+ * 2. every later page asks `until = min(created_at)` of the previous page
14
+ * — INCLUSIVE, so events of that boundary second a cap cut off are
15
+ * fetched again; ids already seen from this relay are deduplicated;
16
+ * 3. a page that brings no new id is the boundary second alone, already
17
+ * seen: `until` steps one second down, past it — and that second is a
18
+ * GAP when the page was as large as the relay's largest page so far
19
+ * (the relay may hold more events of that second than it will ever
20
+ * return: unpaginatable under NIP-01's `until`). A gap is `confirmed`
21
+ * once a later page proves the relay held more than that page;
22
+ * 4. the relay's walk is COMPLETE when a page returns no event at all, or
23
+ * `until` falls below `since`.
24
+ *
25
+ * A short page is never taken as the end: the relay's own cap may be below
26
+ * `limit`. Bounded: at most `maxPages` requests per relay per call; a walk
27
+ * cut off there is NOT complete, and `resumeUntil` says where a follow-up
28
+ * call over `[since, resumeUntil]` picks up.
29
+ *
30
+ * A page resolving `timedOut: true` ends that relay's walk; the result is
31
+ * then `timedOut` (the caller discards the whole pass, AC-PIPE-7) and names
32
+ * the relay in `silentRelays` when the transport reported it silent.
33
+ */
34
+ import { type Filter, type NostrEvent } from '@941design/nostr-events/event';
35
+ import type { RequestWithDeadlineResult } from '@941design/nostr-events/transport/contract';
36
+ /** `limit` asked of every history page. Relays may cap below it; pagination does not rely on it being honoured. */
37
+ export declare const HISTORY_PAGE_LIMIT = 500;
38
+ /** At most this many page requests per relay per history pass; a walk that reaches it is not complete. */
39
+ export declare const HISTORY_MAX_PAGES = 20;
40
+ /**
41
+ * Extra requests allowed when re-walking a window an earlier walk already
42
+ * measured at up to {@link HISTORY_MAX_PAGES} pages: the page re-reading its
43
+ * boundary second and the one that ends the walk. Without them a window of
44
+ * exactly the bound's size would never complete on a re-walk.
45
+ */
46
+ export declare const HISTORY_REWALK_SLACK_PAGES = 2;
47
+ /**
48
+ * The group's live subscription waits for a backlog walk to finish (so its
49
+ * replay cannot run ahead of the oldest-first ingest), but starts regardless
50
+ * once one walk has taken this many history passes (liveness).
51
+ */
52
+ export declare const HISTORY_LIVE_AFTER_WALK_PASSES = 8;
53
+ /** One page request to ONE relay (the caller wraps the transport, e.g. in its re-entrancy guard). */
54
+ export type HistoryPageRequest = (relays: string[], filter: Filter) => Promise<RequestWithDeadlineResult>;
55
+ export interface HistoryPagesOptions {
56
+ readonly pageLimit?: number;
57
+ readonly maxPages?: number;
58
+ /** Consulted before each page; `false` stops every walk (the result is then not complete). */
59
+ readonly active?: () => boolean;
60
+ /** Upper edge reported for a walk that fetched nothing when `filter.until` is open (unix seconds). Default: the local clock. */
61
+ readonly nowSeconds?: number;
62
+ }
63
+ /** A second on which a relay may hold more events than it returned (see step 3). */
64
+ export interface HistoryGap {
65
+ readonly relay: string;
66
+ readonly createdAt: number;
67
+ /** A later page proved the relay held more than the page that stopped on this second. */
68
+ readonly confirmed: boolean;
69
+ }
70
+ export interface HistoryPages {
71
+ /**
72
+ * Every event any relay delivered, deduplicated by id — per id the first copy that verifies (the first delivered
73
+ * when none does) — in first-delivery order of the ids (not filtered or sorted).
74
+ */
75
+ readonly events: NostrEvent[];
76
+ /**
77
+ * Relay provenance (BACKLOG `marmot-use-relay-provenance`): per event id of {@link events}, every relay whose walk
78
+ * delivered it, in `relays` order. Each page is requested from ONE relay, so this is exact without the transport's
79
+ * own `eventRelays` / `DeliveryMeta` (which an adapter may omit).
80
+ */
81
+ readonly eventRelays: ReadonlyMap<string, readonly string[]>;
82
+ /** Some page resolved `timedOut: true`. */
83
+ readonly timedOut: boolean;
84
+ /** Relays whose walk ended on a timed-out page that reported them silent. */
85
+ readonly silentRelays: string[];
86
+ /** Every relay's walk reached its end: nothing in `[filter.since, filter.until]` was left unwalked (gaps aside). */
87
+ readonly complete: boolean;
88
+ /** Seconds some relay may have truncated (see step 3); a complete result says nothing about events stamped on them. */
89
+ readonly gaps: readonly HistoryGap[];
90
+ /** Per relay (in `relays` order): whether its walk ended (`complete`) and whether it returned any event inside the window at all (`advanced`). */
91
+ readonly walks: readonly HistoryWalk[];
92
+ /**
93
+ * When not complete (and not timed out): every event above this
94
+ * `created_at` (up to `filter.until`) was fetched from every relay, so
95
+ * `[filter.since, resumeUntil]` (inclusive) is what a follow-up call must
96
+ * walk. A walk that fetched nothing reports `filter.until`, or
97
+ * `nowSeconds` when that is open.
98
+ */
99
+ readonly resumeUntil?: number;
100
+ }
101
+ export interface HistoryWalk {
102
+ readonly relay: string;
103
+ readonly complete: boolean;
104
+ /** Some page of the walk held an event inside the window — false for a relay answering only with events outside it (e.g. one ignoring `until`). */
105
+ readonly advanced: boolean;
106
+ }
107
+ export declare function fetchHistoryPages(request: HistoryPageRequest, relays: readonly string[], filter: Filter, opts?: HistoryPagesOptions): Promise<HistoryPages>;
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Paginated history fetch over the narrowed `TransportContract`'s
3
+ * `requestWithDeadline` — reusable by every history reader (kind-445 group
4
+ * sync; inbox and history backfills).
5
+ *
6
+ * Relays cap each response server-side (a `max_limit`, commonly ~500,
7
+ * newest first) whatever `limit` the REQ asks for, so one request over a
8
+ * backlog larger than that cap silently returns only its newest part.
9
+ * `fetchHistoryPages` therefore walks EACH relay backwards on its own
10
+ * (a merged multi-relay response cannot say which relay truncated where):
11
+ *
12
+ * 1. page 1 asks `{...filter, limit}`;
13
+ * 2. every later page asks `until = min(created_at)` of the previous page
14
+ * — INCLUSIVE, so events of that boundary second a cap cut off are
15
+ * fetched again; ids already seen from this relay are deduplicated;
16
+ * 3. a page that brings no new id is the boundary second alone, already
17
+ * seen: `until` steps one second down, past it — and that second is a
18
+ * GAP when the page was as large as the relay's largest page so far
19
+ * (the relay may hold more events of that second than it will ever
20
+ * return: unpaginatable under NIP-01's `until`). A gap is `confirmed`
21
+ * once a later page proves the relay held more than that page;
22
+ * 4. the relay's walk is COMPLETE when a page returns no event at all, or
23
+ * `until` falls below `since`.
24
+ *
25
+ * A short page is never taken as the end: the relay's own cap may be below
26
+ * `limit`. Bounded: at most `maxPages` requests per relay per call; a walk
27
+ * cut off there is NOT complete, and `resumeUntil` says where a follow-up
28
+ * call over `[since, resumeUntil]` picks up.
29
+ *
30
+ * A page resolving `timedOut: true` ends that relay's walk; the result is
31
+ * then `timedOut` (the caller discards the whole pass, AC-PIPE-7) and names
32
+ * the relay in `silentRelays` when the transport reported it silent.
33
+ */
34
+ import { safeVerifyEvent } from '@941design/nostr-events/event';
35
+ /** `limit` asked of every history page. Relays may cap below it; pagination does not rely on it being honoured. */
36
+ export const HISTORY_PAGE_LIMIT = 500;
37
+ /** At most this many page requests per relay per history pass; a walk that reaches it is not complete. */
38
+ export const HISTORY_MAX_PAGES = 20;
39
+ /**
40
+ * Extra requests allowed when re-walking a window an earlier walk already
41
+ * measured at up to {@link HISTORY_MAX_PAGES} pages: the page re-reading its
42
+ * boundary second and the one that ends the walk. Without them a window of
43
+ * exactly the bound's size would never complete on a re-walk.
44
+ */
45
+ export const HISTORY_REWALK_SLACK_PAGES = 2;
46
+ /**
47
+ * The group's live subscription waits for a backlog walk to finish (so its
48
+ * replay cannot run ahead of the oldest-first ingest), but starts regardless
49
+ * once one walk has taken this many history passes (liveness).
50
+ */
51
+ export const HISTORY_LIVE_AFTER_WALK_PASSES = 8;
52
+ /** Whether `event` verifies; a frozen delivery is checked on a copy (verification caches on the object). */
53
+ function verifies(event) {
54
+ try {
55
+ return safeVerifyEvent(Object.isExtensible(event) ? event : { ...event });
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ /** Whether two deliveries carry the same signed body; a throwing (hostile) object reads as different. */
62
+ function sameBody(a, b) {
63
+ try {
64
+ return (a.sig === b.sig &&
65
+ a.pubkey === b.pubkey &&
66
+ a.created_at === b.created_at &&
67
+ a.kind === b.kind &&
68
+ a.content === b.content &&
69
+ JSON.stringify(a.tags) === JSON.stringify(b.tags));
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
75
+ export async function fetchHistoryPages(request, relays, filter, opts = {}) {
76
+ const pageLimit = opts.pageLimit ?? HISTORY_PAGE_LIMIT;
77
+ const maxPages = opts.maxPages ?? HISTORY_MAX_PAGES;
78
+ const active = opts.active ?? (() => true);
79
+ const merged = new Map();
80
+ // Whether the kept copy of an id verifies (computed only once a differing copy arrives).
81
+ const keptVerifies = new Map();
82
+ // Duplicates across relays (and pages): the first copy that verifies wins, the first delivered when none does —
83
+ // the transport's rule (requestWithDeadline), applied to the per-relay requests merged here, so a faster relay's
84
+ // tampered body under an honest id cannot hide the valid copy whether or not the adapter verifies.
85
+ const keep = (event) => {
86
+ const kept = merged.get(event.id);
87
+ if (kept === undefined)
88
+ return void merged.set(event.id, event);
89
+ if (kept === event || sameBody(kept, event))
90
+ return;
91
+ let ok = keptVerifies.get(event.id);
92
+ if (ok === undefined)
93
+ keptVerifies.set(event.id, (ok = verifies(kept)));
94
+ if (ok || !verifies(event))
95
+ return;
96
+ merged.set(event.id, event);
97
+ keptVerifies.set(event.id, true);
98
+ };
99
+ const deliveredBy = new Map();
100
+ const gaps = [];
101
+ const since = filter.since;
102
+ // Relays some page of whose walk held an event inside the window.
103
+ const advancedBy = new Set();
104
+ async function walk(relay) {
105
+ const seen = new Set();
106
+ let until = filter.until;
107
+ let largestPage = 0;
108
+ // Gaps found so far, confirmed once a later page brings fresh events.
109
+ const pending = [];
110
+ const settle = (freshAfter) => {
111
+ for (const createdAt of pending.splice(0))
112
+ gaps.push({ relay, createdAt, confirmed: freshAfter });
113
+ };
114
+ const exhausted = () => until !== undefined && since !== undefined && until < since;
115
+ for (let page = 0; page < maxPages; page++) {
116
+ if (!active())
117
+ return settle(false), { kind: 'incomplete', until };
118
+ const pageFilter = { ...filter, limit: pageLimit };
119
+ if (until !== undefined)
120
+ pageFilter.until = until;
121
+ const result = await request([relay], pageFilter);
122
+ if (result.timedOut)
123
+ return settle(false), { kind: 'timedOut', silent: result.silentRelays.includes(relay) };
124
+ let inWindow = 0;
125
+ let fresh = 0;
126
+ let oldest;
127
+ for (const event of result.events) {
128
+ keep(event);
129
+ let by = deliveredBy.get(event.id);
130
+ if (by === undefined)
131
+ deliveredBy.set(event.id, (by = new Set()));
132
+ by.add(relay);
133
+ if ((since !== undefined && event.created_at < since) || (until !== undefined && event.created_at > until))
134
+ continue;
135
+ inWindow += 1;
136
+ if (!seen.has(event.id)) {
137
+ seen.add(event.id);
138
+ fresh += 1;
139
+ }
140
+ oldest = oldest === undefined ? event.created_at : Math.min(oldest, event.created_at);
141
+ }
142
+ // Only an EMPTY page ends the walk: events all outside the window (a
143
+ // relay ignoring `until`, or junk) prove nothing about what is left.
144
+ if (oldest === undefined)
145
+ return settle(false), result.events.length === 0 ? { kind: 'complete' } : { kind: 'incomplete', until };
146
+ advancedBy.add(relay);
147
+ if (fresh > 0) {
148
+ settle(true);
149
+ largestPage = Math.max(largestPage, inWindow);
150
+ until = oldest;
151
+ continue;
152
+ }
153
+ // Nothing new: every event of the page sits on `until` (the boundary
154
+ // second) and was seen. As large as the relay's largest page, it may
155
+ // be the relay's cap cutting that second short.
156
+ if (inWindow >= largestPage)
157
+ pending.push(oldest);
158
+ until = oldest - 1;
159
+ // Stepped below `since`: the window is exhausted, even on the bound's last page.
160
+ if (exhausted())
161
+ return settle(false), { kind: 'complete' };
162
+ }
163
+ settle(false);
164
+ return { kind: 'incomplete', until };
165
+ }
166
+ const outcomes = await Promise.all(relays.map((relay) => walk(relay)));
167
+ const silentRelays = relays.filter((_, i) => {
168
+ const outcome = outcomes[i];
169
+ return outcome.kind === 'timedOut' && outcome.silent;
170
+ });
171
+ const timedOut = outcomes.some((o) => o.kind === 'timedOut');
172
+ // The resume edge is the HIGHEST unfinished walk's edge: each relay has served everything above its own.
173
+ const openEdge = filter.until ?? opts.nowSeconds ?? Math.floor(Date.now() / 1000);
174
+ let resumeUntil;
175
+ for (const outcome of outcomes) {
176
+ if (outcome.kind !== 'incomplete')
177
+ continue;
178
+ const edge = outcome.until ?? openEdge;
179
+ resumeUntil = resumeUntil === undefined ? edge : Math.max(resumeUntil, edge);
180
+ }
181
+ const eventRelays = new Map();
182
+ for (const id of merged.keys())
183
+ eventRelays.set(id, Object.freeze(relays.filter((relay) => deliveredBy.get(id)?.has(relay) === true)));
184
+ return {
185
+ events: [...merged.values()],
186
+ eventRelays,
187
+ timedOut,
188
+ silentRelays,
189
+ complete: outcomes.every((o) => o.kind === 'complete'),
190
+ gaps,
191
+ walks: relays.map((relay, i) => ({ relay, complete: outcomes[i].kind === 'complete', advanced: advancedBy.has(relay) })),
192
+ ...(timedOut || resumeUntil === undefined ? {} : { resumeUntil }),
193
+ };
194
+ }
@@ -0,0 +1,19 @@
1
+ import type { Signer } from '@941design/nostr-events/signer';
2
+ import { type InboxRelayDeps } from '../invitations/index.js';
3
+ /** What `extensions.sendInboxRumor` reports for its one publish. */
4
+ export interface InboxRumorDelivery {
5
+ /**
6
+ * `delivered` — a relay of the recipient's inbox plane accepted the wrap; `retryable` — the relay lookup timed
7
+ * out (`nip17-timed-out` / `nip65-timed-out`) or no relay accepted it yet (`publish-failed`); `failed` — the
8
+ * recipient has no inbox relay (`no-inbox-relays`) or every relay refused it for good (`publish-refused`).
9
+ */
10
+ readonly status: 'delivered' | 'retryable' | 'failed';
11
+ readonly reason?: string;
12
+ /** The inbox relays the wrap was published to (absent when nothing was published). */
13
+ readonly relays?: readonly string[];
14
+ }
15
+ export interface InboxSendDeps extends InboxRelayDeps {
16
+ /** The budgeted account signer, routed through the re-entrancy guard. */
17
+ readonly signer: Signer;
18
+ }
19
+ export declare function sendInboxRumor(deps: InboxSendDeps, input: unknown): Promise<InboxRumorDelivery>;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * `extensions.sendInboxRumor({ to, rumor })` (AC-MX-3): one gift-wrapped rumor to one
3
+ * recipient's inbox, over marmot's own inbox plane — `resolveInboxRelays` (kind-10050, else 10002 read set, else
4
+ * `relays.defaults`; never a group relay), sealed by the client's budgeted account signer, published once and
5
+ * classified by `classifyPublish`. A best-effort, at-most-once send: nothing is persisted and nothing is
6
+ * retried — the returned status says whether the caller should try again.
7
+ *
8
+ * Rumor kinds marmot handles itself (`RUMOR_KINDS`) are refused `reserved-kind` before any signer or transport
9
+ * call, so this path can never inject a Welcome, enrolment request or KeyPackage offer. The rumor must be the
10
+ * account's own (its `pubkey`) with its NIP-01 `id`: a recipient's unwrap rejects anything else, so it is
11
+ * refused here (`invalid-options`) rather than silently undeliverable.
12
+ */
13
+ import { getEventHash, isPubkey, isRumor } from '@941design/nostr-events/event';
14
+ import { wrap as giftWrap } from '@941design/nostr-events/gift-wrap';
15
+ import { isReservedRumorKind } from '../inbox/index.js';
16
+ import { resolveInboxRelays } from '../invitations/index.js';
17
+ import { classifyPublish, MarmotError } from '../shared/index.js';
18
+ function invalid(message, details) {
19
+ return new MarmotError('invalid-options', `extensions.sendInboxRumor: ${message}`, details === undefined ? undefined : { details });
20
+ }
21
+ function delivery(status, reason, relays) {
22
+ return Object.freeze({
23
+ status,
24
+ ...(reason === undefined ? {} : { reason }),
25
+ ...(relays === undefined ? {} : { relays: Object.freeze([...relays]) }),
26
+ });
27
+ }
28
+ export async function sendInboxRumor(deps, input) {
29
+ if (typeof input !== 'object' || input === null)
30
+ throw invalid('input must be { to, rumor }');
31
+ const { to, rumor } = input;
32
+ if (typeof rumor !== 'object' || rumor === null)
33
+ throw invalid('rumor must be a rumor object');
34
+ const kind = rumor.kind;
35
+ if (typeof kind !== 'number' || !Number.isInteger(kind))
36
+ throw invalid('rumor.kind must be an integer');
37
+ // First of all the semantic checks: a marmot-native kind never reaches the signer or a relay through here.
38
+ if (isReservedRumorKind(kind)) {
39
+ throw new MarmotError('reserved-kind', `extensions.sendInboxRumor: kind ${kind} is a marmot rumor kind (RUMOR_KINDS) and cannot be sent through this path`, { details: { kind } });
40
+ }
41
+ if (!isPubkey(to))
42
+ throw invalid('to must be a 64-char lower-case hex pubkey', { reason: 'invalid-recipient' });
43
+ if (!isRumor(rumor))
44
+ throw invalid('rumor must be a NIP-59 rumor (id, pubkey, kind, created_at, tags, content)', { reason: 'invalid-rumor' });
45
+ // Only the six rumor fields go into the seal (never a stray `sig` or extra member of the caller's object).
46
+ const plain = { id: rumor.id, pubkey: rumor.pubkey, kind: rumor.kind, created_at: rumor.created_at, tags: rumor.tags.map((t) => [...t]), content: rumor.content };
47
+ const self = await deps.signer.getPublicKey();
48
+ if (plain.pubkey !== self)
49
+ throw invalid('rumor.pubkey must be the account pubkey (the seal author)', { reason: 'foreign-author' });
50
+ if (getEventHash(plain) !== plain.id)
51
+ throw invalid('rumor.id is not the NIP-01 hash of the rumor', { reason: 'invalid-id' });
52
+ const resolution = await resolveInboxRelays(deps, to);
53
+ if (resolution.kind === 'none')
54
+ return delivery('failed', 'no-inbox-relays');
55
+ if (resolution.kind === 'transient')
56
+ return delivery('retryable', resolution.reason);
57
+ const relays = [...resolution.relays];
58
+ const wrapped = await giftWrap({ senderSigner: deps.signer, recipientPubkey: to, rumor: plain });
59
+ let responses;
60
+ try {
61
+ responses = await deps.transport.publish(relays, wrapped);
62
+ }
63
+ catch {
64
+ // A thrown network error is transient.
65
+ return delivery('retryable', 'publish-failed', relays);
66
+ }
67
+ const { outcome } = classifyPublish(relays, responses);
68
+ if (outcome === 'accepted')
69
+ return delivery('delivered', undefined, relays);
70
+ return outcome === 'terminal' ? delivery('failed', 'publish-refused', relays) : delivery('retryable', 'publish-failed', relays);
71
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Public barrel of the `client` module. Only what is listed here is part of
3
+ * `@941design/marmot`'s surface (docs/client-api.md); `getClientContext` and
4
+ * the other internals of `create-client.ts` stay module-private.
5
+ */
6
+ export { createMarmotClient, type ClientClock, type ClientOptions, type ClientTimers, type ConfirmContext, type ConfirmHook, type ConfirmKind, type GroupDisbanded, type GroupNotification, type ClientStores, type EncryptedMedia, type EventVerifier, type GroupIntent, type GroupSnapshot, type InboxHandler, type InboxRumorDelivery, type IngestDisposition, type LeafInfo, type MarmotClient, type MarmotClientEventName, type MarmotClientEvents, type MarmotClientOptions, type MarmotGroup, type OrderingKey, type PendingIntent, type RelayOptions, type WelcomeManifest, } from './create-client.js';
7
+ export { MarmotError, isMarmotError, MARMOT_ERROR_CODES, type MarmotErrorCode, RUMOR_KINDS, type RumorKind, type RumorKindConstants, } from '../shared/index.js';
8
+ export { permissions } from './permissions.js';
9
+ export { groupProfileProposal, type GroupProfile } from './group-profile.js';
10
+ export { keyPackageRefOf } from '../key-packages/key-package-ref.js';
11
+ export { createMemoryHistoryBackend } from '../history/index.js';
12
+ export type { AppliedNotification, GroupDisbandedNotification, HistoryBackend, HistoryEntry, LeafEquivocationNotification, LeafRemovalWithdrawnNotification, LeafRemovedNotification, MessageNotification, MessageWithdrawnNotification, OwnChange, OwnChangeLostNotification, OwnChangeLostReason, OwnChangeReappliedNotification, OwnChangeWithdrawnNotification, WithdrawnNotification, } from '../history/index.js';
13
+ export { createMemoryMediaCache } from '../media/index.js';
14
+ export type { EncryptMediaOptions, MediaCache } from '../media/index.js';
15
+ export type { CreateGroupGate, CreateGroupGateResult } from './before-create-group.js';
16
+ export type { BeforePublishContext, BeforePublishHook, BeforePublishSkipped, BeforePublishSkippedReason, PublishBarrier } from './before-publish-hooks.js';
17
+ export type { MaintenanceKind, PendingInvitation, PendingProposal, ProposalCallback, ProposalDecision, WelcomeOutcome } from '../invitations/index.js';
18
+ export type { InboxDisposition, InboxRumorHandler, RumorDisposition } from '../inbox/index.js';
19
+ export type { KeyPackageOffer } from '../invitations/index.js';
20
+ export type { DeviceForgetGroupOutcome, DeviceForgetOutcome, DeviceInfo, DeviceKeyRotationOutcome, DeviceKeyRotationOutcomeStatus, DeviceMaintenanceKind, DeviceTombstone, EnrolmentApprovalOutcome, EnrolmentGroupOutcome, EnrolmentPrompt, EnrolmentRequestHandle, EnrolmentRequestOptions, } from '../account/index.js';
21
+ export type { DeviceKeyRotationGroupOutcome } from '../key-packages/index.js';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Public barrel of the `client` module. Only what is listed here is part of
3
+ * `@941design/marmot`'s surface (docs/client-api.md); `getClientContext` and
4
+ * the other internals of `create-client.ts` stay module-private.
5
+ */
6
+ export { createMarmotClient, } from './create-client.js';
7
+ export { MarmotError, isMarmotError, MARMOT_ERROR_CODES, RUMOR_KINDS, } from '../shared/index.js';
8
+ export { permissions } from './permissions.js';
9
+ export { groupProfileProposal } from './group-profile.js';
10
+ export { keyPackageRefOf } from '../key-packages/key-package-ref.js';
11
+ // S10 (AC-HIST-3, AC-MEDIA-2): the history-media seams and their memory implementations.
12
+ export { createMemoryHistoryBackend } from '../history/index.js';
13
+ export { createMemoryMediaCache } from '../media/index.js';
@@ -0,0 +1,82 @@
1
+ /**
2
+ * `MarmotGroup.ingest` (S3): durable cursor, terminal-ledger dedup, the
3
+ * `verifier` seam, the ADR-012 post-apply proof gate, and the history-sync /
4
+ * live-subscription loop wired at runtime creation
5
+ * (AC-PIPE-4..7, AC-PIPE-9, AC-PIPE-14, AC-PROOF-1..3).
6
+ *
7
+ * `ingestEvents` is the shared body of `MarmotGroup.ingest(events)` (called
8
+ * through `rt.run('ingest', ...)` by `group-runtime.ts`'s handle — already
9
+ * per-group serialised, AC-PIPE-4) AND of every sync-driven batch below
10
+ * (`opts.fromSync: true`, which additionally advances the persisted cursor).
11
+ *
12
+ * `startGroupSync`/`stopGroupSync` run the history-then-live loop: one
13
+ * history pass paginated per relay over bounded `requestWithDeadline` pages
14
+ * (`history-pages.ts`; discarding the whole pass on any `timedOut` page,
15
+ * AC-PIPE-7, and tracking consecutive per-relay silence,
16
+ * AC-PIPE-14), then a live `subscription` over the FULL relay plane
17
+ * (exclusion is history-only) until `stopGroupSync`/dispose tears it down.
18
+ */
19
+ import type { NostrEvent } from '@941design/nostr-events/event';
20
+ import type { IngestDisposition } from './create-client.js';
21
+ import type { GroupRuntime } from './group-runtime.js';
22
+ export interface IngestOptions {
23
+ /** True for a history/live sync-driven batch: additionally advances the persisted cursor. */
24
+ readonly fromSync?: boolean;
25
+ /** Internal: the retry after {@link restageExcludedProposals} — no resume first, and no second re-stage. */
26
+ readonly restaged?: boolean;
27
+ /**
28
+ * Internal ({@link treeFedPass}): no events, only the engine's tree-fed convergence pass (and its pool sweep) over
29
+ * the history tree it holds, judged by the proof gate and persisted like any batch. No resume first.
30
+ */
31
+ readonly treeFed?: boolean;
32
+ }
33
+ /**
34
+ * The tree-fed convergence pass over the engine's current history tree, as an ordinary batch of no events (proof gate,
35
+ * persistence, notifications). The engine runs it on every ingest; this runs it on its own, after a rebuild changed
36
+ * the tree without any envelope to trigger one (the pending-restore resolution, client/pending-leaf.ts). Inside a
37
+ * group operation.
38
+ */
39
+ export declare function treeFedPass(rt: GroupRuntime): Promise<void>;
40
+ /**
41
+ * The engine's convergence continuation: input that arrived after a convergence
42
+ * deadline is retained and only released by `driveConvergence()`. The released
43
+ * envelopes are not trusted as applied by that drain — the engine is rolled back
44
+ * to the durable state and they (with anything it was pooling) are re-ingested
45
+ * through {@link ingestEvents}, so the proof gate, persistence, ledger and cursor
46
+ * apply exactly as for any other delivery.
47
+ */
48
+ export declare function drainConvergence(rt: GroupRuntime): Promise<void>;
49
+ /**
50
+ * S20: settles the group's held removal at its settle time even when no further input arrives (a removed device
51
+ * gets nothing it can read): armed on load and whenever a removal is newly held. A timer that fires early (the
52
+ * client clock lags) re-arms. Never throws.
53
+ */
54
+ export declare function scheduleRemovalSettle(rt: GroupRuntime): void;
55
+ export declare function ingestEvents(rt: GroupRuntime, events: readonly NostrEvent[], opts?: IngestOptions): Promise<readonly IngestDisposition[]>;
56
+ /**
57
+ * The live subscription listens on the routing it was opened with; a commit
58
+ * (inbound or own) changing the group's relays or Nostr group id would leave
59
+ * it listening where the group no longer publishes. Restarts the sync on the
60
+ * new routing: the old subscription is dropped, and a history pass from the
61
+ * cursor over the new plane runs now (not on the backoff — nothing failed, and
62
+ * not after a pass already in flight: it supersedes it), ending in a new
63
+ * subscription. A pass already in flight on the old routing notices the change
64
+ * and asks for a rerun (see `runHistoryPass`). Never throws:
65
+ * it runs right after a batch or confirmation was persisted.
66
+ */
67
+ export declare function restartSyncOnRoutingChange(rt: GroupRuntime): void;
68
+ /** Idempotent: a no-op once already started (a cached, still-live `groups.get` never restarts it). */
69
+ export declare function startGroupSync(rt: GroupRuntime): void;
70
+ /**
71
+ * Unsubscribes the live subscription and clears any pending history-retry
72
+ * timer. Idempotent. The transport unsubscribe runs last: if it throws, the
73
+ * sync is already stopped and the timer already cleared.
74
+ */
75
+ export declare function stopGroupSync(rt: GroupRuntime): void;
76
+ /**
77
+ * A history pass from the persisted cursor, now — used once a blocked
78
+ * confirmation clears so that events dropped as `group-busy` meanwhile (the
79
+ * cursor holds them) are refetched. A no-op when not syncing, or when a
80
+ * retry pass is already scheduled (it reads the same cursor).
81
+ */
82
+ export declare function requestHistoryResync(rt: GroupRuntime): void;