@estiva-app/conversation 0.1.0 → 0.2.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.
- package/CHANGELOG.md +30 -0
- package/README.md +20 -4
- package/dist/builders.d.ts.map +1 -1
- package/dist/builders.js +1 -2
- package/dist/builders.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/dist/kinds.d.ts +8 -0
- package/dist/kinds.d.ts.map +1 -1
- package/dist/kinds.js +8 -0
- package/dist/kinds.js.map +1 -1
- package/dist/membership.d.ts +132 -0
- package/dist/membership.d.ts.map +1 -0
- package/dist/membership.js +271 -0
- package/dist/membership.js.map +1 -0
- package/dist/readState.d.ts +214 -0
- package/dist/readState.d.ts.map +1 -0
- package/dist/readState.js +345 -0
- package/dist/readState.js.map +1 -0
- package/dist/strength.d.ts +2 -0
- package/dist/strength.d.ts.map +1 -1
- package/dist/strength.js +7 -3
- package/dist/strength.js.map +1 -1
- package/dist/unread.d.ts +54 -0
- package/dist/unread.d.ts.map +1 -0
- package/dist/unread.js +50 -0
- package/dist/unread.js.map +1 -0
- package/package.json +2 -2
- package/src/builders.ts +1 -3
- package/src/index.ts +69 -1
- package/src/kinds.ts +10 -0
- package/src/membership.ts +328 -0
- package/src/readState.ts +486 -0
- package/src/strength.ts +8 -3
- package/src/unread.ts +85 -0
package/src/readState.ts
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read state — SPEC §11, NIP-RS: per person, not per app.
|
|
3
|
+
*
|
|
4
|
+
* `kind:30078` blobs, NIP-44 encrypted to self, **one per installation**,
|
|
5
|
+
* merged by taking the maximum timestamp per context. Reading a file in Ship
|
|
6
|
+
* marks it read in Peek because both name it the same way (§11.1) and both
|
|
7
|
+
* merge every slot.
|
|
8
|
+
*
|
|
9
|
+
* Ported from Peek's `readState.ts` and `readStateMerge.ts` and Ship's
|
|
10
|
+
* `readState.ts`, which had diverged. Where they differed the SPEC decided:
|
|
11
|
+
*
|
|
12
|
+
* - **The cap is in bytes, not a count** (§11.6). `/nip44/encrypt` refuses a
|
|
13
|
+
* plaintext over 65,535 bytes, and on production a slot is refused at
|
|
14
|
+
* ~771 contexts, so Ship's 10,000-context cap could never fire. Eviction is
|
|
15
|
+
* deterministic to the tie, so a merge does not hand an evicted context back.
|
|
16
|
+
* - **A slot whose coordinate carries another `client_id` is reported**, so
|
|
17
|
+
* the app can rotate rather than overwrite another installation on every
|
|
18
|
+
* write (Peek had it; Ship did not).
|
|
19
|
+
* - **An unreachable relay is not "no slots"**, and our own slot existing but
|
|
20
|
+
* not decrypting is not "first run" (Ship had both apart; kept).
|
|
21
|
+
*
|
|
22
|
+
* Nothing here opens a socket or touches the browser: the relay read, the
|
|
23
|
+
* signer, NIP-44 and storage are parameters.
|
|
24
|
+
*/
|
|
25
|
+
import type { SignedEvent, UnsignedEvent } from '@estiva-app/protocol'
|
|
26
|
+
import { FILE_ADDRESS as ADDRESS_RE, FOLDER_ID as UUID_RE, KIND_APP_DATA } from './kinds.js'
|
|
27
|
+
import type { QueryFn } from './decorations.js'
|
|
28
|
+
|
|
29
|
+
/** NIP-RS's own `t` tag. */
|
|
30
|
+
export const READ_STATE_TAG = 'read-state'
|
|
31
|
+
|
|
32
|
+
/** The `d`-tag prefix the relay's NIP-RS predicate keys on (§11.6). */
|
|
33
|
+
export const READ_STATE_D_PREFIX = 'read-state:'
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Limits from NIP-RS and the reference implementation (§11.6).
|
|
37
|
+
* `MAX_CONTEXTS` binds only the merged view across slots: one blob meets
|
|
38
|
+
* {@link MAX_CONTEXTS_BYTES} far sooner.
|
|
39
|
+
*/
|
|
40
|
+
export const MAX_CONTEXTS = 10_000
|
|
41
|
+
export const MAX_CONTEXT_ID_BYTES = 256
|
|
42
|
+
export const MAX_TIMESTAMP = 4_294_967_295
|
|
43
|
+
export const MAX_CLIENT_ID_BYTES = 64
|
|
44
|
+
|
|
45
|
+
/** The plaintext ceiling `/nip44/encrypt` enforces (SPEC §12.5), in bytes of UTF-8. */
|
|
46
|
+
export const MAX_BLOB_BYTES = 65_535
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The bytes the `contexts` map may occupy: the ceiling less the envelope, sized
|
|
50
|
+
* at the **longest legal `client_id`**, so every installation holding the same
|
|
51
|
+
* contexts evicts the same ones.
|
|
52
|
+
*/
|
|
53
|
+
export const MAX_CONTEXTS_BYTES =
|
|
54
|
+
MAX_BLOB_BYTES - (JSON.stringify({ v: 1, client_id: 'x'.repeat(MAX_CLIENT_ID_BYTES), contexts: {} }).length - 2)
|
|
55
|
+
|
|
56
|
+
/** A horizon of 90 days: what both apps used. NIP-RS fixes none (§11.6). */
|
|
57
|
+
export const READ_STATE_HORIZON_DAYS = 90
|
|
58
|
+
|
|
59
|
+
const EVENT_ID_RE = /^[0-9a-f]{64}$/
|
|
60
|
+
const SLOT_ID_RE = /^[0-9a-f]{32}$/
|
|
61
|
+
|
|
62
|
+
/** Bytes of UTF-8 — counted here, since a package may not reach for `TextEncoder` (ADR 0002). */
|
|
63
|
+
function utf8(value: string): number {
|
|
64
|
+
let bytes = 0
|
|
65
|
+
for (const char of value) {
|
|
66
|
+
const code = char.codePointAt(0) ?? 0
|
|
67
|
+
bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4
|
|
68
|
+
}
|
|
69
|
+
return bytes
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ── Context identifiers — §11.1 ─────────────────────────────────────────────
|
|
73
|
+
|
|
74
|
+
/** A channel's context: the **bare** channel uuid. Undefined for anything else, never coerced. */
|
|
75
|
+
export function channelContext(channelUuid: string | null | undefined): string | undefined {
|
|
76
|
+
if (!channelUuid) return undefined
|
|
77
|
+
const value = channelUuid.toLowerCase()
|
|
78
|
+
return UUID_RE.test(value) ? value : undefined
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A file's context: its **bare** address, `d` verbatim (FOL-16). */
|
|
82
|
+
export function fileContext(address: string | null | undefined): string | undefined {
|
|
83
|
+
if (!address || utf8(address) > MAX_CONTEXT_ID_BYTES) return undefined
|
|
84
|
+
return ADDRESS_RE.test(address) ? address : undefined
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `thread:<root-event-id>`, NIP-RS's own scheme. */
|
|
88
|
+
export function threadContext(rootEventId: string | null | undefined): string | undefined {
|
|
89
|
+
if (!rootEventId) return undefined
|
|
90
|
+
const value = rootEventId.toLowerCase()
|
|
91
|
+
return EVENT_ID_RE.test(value) ? `thread:${value}` : undefined
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `msg:<event-id>`, NIP-RS's own scheme. */
|
|
95
|
+
export function messageContext(eventId: string | null | undefined): string | undefined {
|
|
96
|
+
if (!eventId) return undefined
|
|
97
|
+
const value = eventId.toLowerCase()
|
|
98
|
+
return EVENT_ID_RE.test(value) ? `msg:${value}` : undefined
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Epoch ms → the unix **seconds** NIP-RS stores, clamped to its range. */
|
|
102
|
+
export function toContextSeconds(atMs: number): number {
|
|
103
|
+
const seconds = Math.floor(atMs / 1000)
|
|
104
|
+
if (!Number.isFinite(seconds) || seconds < 0) return 0
|
|
105
|
+
return Math.min(seconds, MAX_TIMESTAMP)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Is this a context id worth putting in a grow-only blob: a channel uuid, a
|
|
110
|
+
* file address, or `thread:`/`msg:` with 64 lowercase hex. The reserved
|
|
111
|
+
* `folder:` is refused until §11.5 specifies it.
|
|
112
|
+
*/
|
|
113
|
+
export function isPublishableContextId(id: string): boolean {
|
|
114
|
+
if (id.length === 0 || utf8(id) > MAX_CONTEXT_ID_BYTES) return false
|
|
115
|
+
if (id.startsWith('thread:')) return EVENT_ID_RE.test(id.slice('thread:'.length))
|
|
116
|
+
if (id.startsWith('msg:')) return EVENT_ID_RE.test(id.slice('msg:'.length))
|
|
117
|
+
return UUID_RE.test(id) || ADDRESS_RE.test(id)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const isTimestamp = (value: unknown): value is number =>
|
|
121
|
+
typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= MAX_TIMESTAMP
|
|
122
|
+
|
|
123
|
+
// ── Slot identity ───────────────────────────────────────────────────────────
|
|
124
|
+
|
|
125
|
+
/** This installation's slot. */
|
|
126
|
+
export interface SlotIdentity {
|
|
127
|
+
/** 32 lowercase hex; the `d` tag is `read-state:<slotId>`. */
|
|
128
|
+
slotId: string
|
|
129
|
+
/** A stable name for this installation, 1–64 characters. */
|
|
130
|
+
clientId: string
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The storage a slot lives in — `localStorage` in a browser. It may throw. */
|
|
134
|
+
export interface SlotStorage {
|
|
135
|
+
getItem(key: string): string | null
|
|
136
|
+
setItem(key: string, value: string): void
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** `n` cryptographically random bytes — `(n) => crypto.getRandomValues(new Uint8Array(n))`. */
|
|
140
|
+
export type RandomBytes = (n: number) => Uint8Array
|
|
141
|
+
|
|
142
|
+
const hexOf = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
143
|
+
|
|
144
|
+
/** Where a slot lives and how a new one is minted. */
|
|
145
|
+
export interface SlotSource {
|
|
146
|
+
storage: SlotStorage | undefined
|
|
147
|
+
/** The app's own key (`estiva-peek:read-state-slot`, `ship.readstate.slot`), so it keeps the slot it has. */
|
|
148
|
+
storageKey: string
|
|
149
|
+
/** Names the app in a new `client_id`: `peek` → `peek-1a2b3c4d`. */
|
|
150
|
+
clientPrefix: string
|
|
151
|
+
random: RandomBytes
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* This installation's slot, minted once and reused.
|
|
156
|
+
*
|
|
157
|
+
* Storage must survive a restart — a slot minted per session piles up past the
|
|
158
|
+
* reference client's eight. A storage that throws degrades to an ephemeral
|
|
159
|
+
* slot rather than failing the app.
|
|
160
|
+
*/
|
|
161
|
+
export function loadSlotIdentity(source: SlotSource): SlotIdentity {
|
|
162
|
+
const { storage, storageKey, clientPrefix, random } = source
|
|
163
|
+
// ASCII and short, so the `client_id` is under the byte limit the reload checks — a longer one would mint a new slot every load.
|
|
164
|
+
if (!/^[a-z0-9-]{1,55}$/.test(clientPrefix)) throw new Error(`client prefix must be 1–55 of [a-z0-9-], got ${JSON.stringify(clientPrefix)}`)
|
|
165
|
+
const fresh = (): SlotIdentity => ({ slotId: hexOf(random(16)), clientId: `${clientPrefix}-${hexOf(random(4))}` })
|
|
166
|
+
if (!storage) return fresh()
|
|
167
|
+
try {
|
|
168
|
+
const raw = storage.getItem(storageKey)
|
|
169
|
+
if (raw) {
|
|
170
|
+
const parsed = JSON.parse(raw) as Partial<SlotIdentity>
|
|
171
|
+
if (
|
|
172
|
+
typeof parsed.slotId === 'string' &&
|
|
173
|
+
SLOT_ID_RE.test(parsed.slotId) &&
|
|
174
|
+
typeof parsed.clientId === 'string' &&
|
|
175
|
+
parsed.clientId.length >= 1 &&
|
|
176
|
+
utf8(parsed.clientId) <= MAX_CLIENT_ID_BYTES
|
|
177
|
+
) {
|
|
178
|
+
return { slotId: parsed.slotId, clientId: parsed.clientId }
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
} catch {
|
|
182
|
+
// Unreadable: mint below.
|
|
183
|
+
}
|
|
184
|
+
const identity = fresh()
|
|
185
|
+
try {
|
|
186
|
+
storage.setItem(storageKey, JSON.stringify(identity))
|
|
187
|
+
} catch {
|
|
188
|
+
// Ephemeral slot.
|
|
189
|
+
}
|
|
190
|
+
return identity
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* A new slot id with the same `client_id`, persisted. For one case: our
|
|
195
|
+
* coordinate carries another installation's `client_id`, and writing to it
|
|
196
|
+
* would overwrite theirs on every write.
|
|
197
|
+
*/
|
|
198
|
+
export function rotateSlotId(identity: SlotIdentity, source: Omit<SlotSource, 'clientPrefix'>): SlotIdentity {
|
|
199
|
+
const { storage, storageKey, random } = source
|
|
200
|
+
const rotated: SlotIdentity = { slotId: hexOf(random(16)), clientId: identity.clientId }
|
|
201
|
+
try {
|
|
202
|
+
storage?.setItem(storageKey, JSON.stringify(rotated))
|
|
203
|
+
} catch {
|
|
204
|
+
// Ephemeral.
|
|
205
|
+
}
|
|
206
|
+
return rotated
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** `read-state:<slot-id>`. */
|
|
210
|
+
export function readStateDTag(slotId: string): string {
|
|
211
|
+
if (!SLOT_ID_RE.test(slotId)) throw new Error(`slot id must be 32 lowercase hex, got ${JSON.stringify(slotId)}`)
|
|
212
|
+
return `${READ_STATE_D_PREFIX}${slotId}`
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ── The blob ────────────────────────────────────────────────────────────────
|
|
216
|
+
|
|
217
|
+
/** A decrypted NIP-RS blob. */
|
|
218
|
+
export interface ReadStateBlob {
|
|
219
|
+
v: 1
|
|
220
|
+
client_id: string
|
|
221
|
+
/** Context id → unix seconds. */
|
|
222
|
+
contexts: Record<string, number>
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Parse a decrypted blob, dropping entries it cannot trust and keeping the
|
|
227
|
+
* rest. Undefined only when it is not a v1 blob at all — which the caller must
|
|
228
|
+
* keep apart from an empty one, so as not to republish over it.
|
|
229
|
+
*/
|
|
230
|
+
export function parseReadStateBlob(plaintext: string | undefined): ReadStateBlob | undefined {
|
|
231
|
+
if (!plaintext) return undefined
|
|
232
|
+
let raw: unknown
|
|
233
|
+
try {
|
|
234
|
+
raw = JSON.parse(plaintext)
|
|
235
|
+
} catch {
|
|
236
|
+
return undefined
|
|
237
|
+
}
|
|
238
|
+
if (typeof raw !== 'object' || raw === null) return undefined
|
|
239
|
+
const blob = raw as Partial<ReadStateBlob>
|
|
240
|
+
if (blob.v !== 1) return undefined
|
|
241
|
+
const clientId =
|
|
242
|
+
typeof blob.client_id === 'string' && blob.client_id.length >= 1 && utf8(blob.client_id) <= MAX_CLIENT_ID_BYTES ? blob.client_id : ''
|
|
243
|
+
const contexts: Record<string, number> = {}
|
|
244
|
+
const source = typeof blob.contexts === 'object' && blob.contexts !== null ? blob.contexts : {}
|
|
245
|
+
for (const [key, value] of Object.entries(source as Record<string, unknown>)) {
|
|
246
|
+
if (isPublishableContextId(key) && isTimestamp(value)) contexts[key] = value
|
|
247
|
+
}
|
|
248
|
+
return { v: 1, client_id: clientId, contexts }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Serialize for encryption, keys sorted, so an unchanged set is an unchanged string. */
|
|
252
|
+
export function serializeReadStateBlob(blob: ReadStateBlob): string {
|
|
253
|
+
const contexts: Record<string, number> = {}
|
|
254
|
+
for (const key of Object.keys(blob.contexts).sort()) contexts[key] = blob.contexts[key]
|
|
255
|
+
return JSON.stringify({ v: blob.v, client_id: blob.client_id, contexts })
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** A context map trimmed to the byte ceiling, and what that cost. */
|
|
259
|
+
export interface CappedContexts {
|
|
260
|
+
contexts: Record<string, number>
|
|
261
|
+
/** `JSON.stringify(contexts)` in bytes of UTF-8, braces included. */
|
|
262
|
+
bytes: number
|
|
263
|
+
/** What was dropped, newest first. Empty is the normal case. */
|
|
264
|
+
evicted: string[]
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const byNewestThenKey = (contexts: Readonly<Record<string, number>>) => (a: string, b: string) =>
|
|
268
|
+
contexts[b] - contexts[a] || (a < b ? -1 : a > b ? 1 : 0)
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Trim a context map to the byte budget, newest marker first, ties by key.
|
|
272
|
+
* Dropping the oldest marker costs one conversation looking unread; a blob
|
|
273
|
+
* over the ceiling is refused whole and costs all of them. Deterministic and
|
|
274
|
+
* idempotent, so a merge does not undo an eviction.
|
|
275
|
+
*/
|
|
276
|
+
export function capContextsToBytes(contexts: Readonly<Record<string, number>>, budget: number = MAX_CONTEXTS_BYTES): CappedContexts {
|
|
277
|
+
const cost = (key: string, value: number) => utf8(JSON.stringify(key)) + 1 + String(value).length
|
|
278
|
+
const keys = Object.keys(contexts).sort(byNewestThenKey(contexts))
|
|
279
|
+
const kept: Record<string, number> = {}
|
|
280
|
+
let bytes = 2
|
|
281
|
+
for (let i = 0; i < keys.length; i++) {
|
|
282
|
+
const key = keys[i]
|
|
283
|
+
const next = bytes + cost(key, contexts[key]) + (i === 0 ? 0 : 1)
|
|
284
|
+
if (next > budget) return { contexts: kept, bytes, evicted: keys.slice(i) }
|
|
285
|
+
kept[key] = contexts[key]
|
|
286
|
+
bytes = next
|
|
287
|
+
}
|
|
288
|
+
return { contexts: kept, bytes, evicted: [] }
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Apply markers, taking the later of each (§11.4: never lower one), then cap.
|
|
293
|
+
* Unpublishable ids and out-of-range timestamps are dropped.
|
|
294
|
+
*/
|
|
295
|
+
export function advanceContexts(current: Readonly<Record<string, number>>, updates: Readonly<Record<string, number>>): CappedContexts {
|
|
296
|
+
const next: Record<string, number> = { ...current }
|
|
297
|
+
for (const [id, seconds] of Object.entries(updates)) {
|
|
298
|
+
if (!isPublishableContextId(id) || !isTimestamp(seconds)) continue
|
|
299
|
+
if (next[id] === undefined || seconds > next[id]) next[id] = seconds
|
|
300
|
+
}
|
|
301
|
+
return capContextsToBytes(next)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// ── The event ───────────────────────────────────────────────────────────────
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* The unsigned `kind:30078` for one slot: exactly one `d`, exactly one
|
|
308
|
+
* `["t","read-state"]` (§11.6 — an event that misses the shape is stored as an
|
|
309
|
+
* ordinary one and merged by nobody), and no `h`.
|
|
310
|
+
*/
|
|
311
|
+
export function buildReadStateEvent(pubkey: string, nowMs: number, slotId: string, ciphertext: string): UnsignedEvent {
|
|
312
|
+
return {
|
|
313
|
+
pubkey,
|
|
314
|
+
created_at: Math.floor(nowMs / 1000),
|
|
315
|
+
kind: KIND_APP_DATA,
|
|
316
|
+
tags: [
|
|
317
|
+
['d', readStateDTag(slotId)],
|
|
318
|
+
['t', READ_STATE_TAG],
|
|
319
|
+
],
|
|
320
|
+
content: ciphertext,
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Every slot **this person** owns within the horizon. One pubkey and no list
|
|
326
|
+
* variant: NIP-RS is not a read-receipt protocol.
|
|
327
|
+
*/
|
|
328
|
+
export function allSlotsFilter(pubkey: string, nowMs: number, horizonDays: number = READ_STATE_HORIZON_DAYS): Record<string, unknown> {
|
|
329
|
+
const since = toContextSeconds(nowMs) - Math.round(horizonDays * 86_400)
|
|
330
|
+
return { kinds: [KIND_APP_DATA], authors: [pubkey], '#t': [READ_STATE_TAG], since: Math.max(0, since) }
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ── Merge — §11.3, §11.4 ────────────────────────────────────────────────────
|
|
334
|
+
|
|
335
|
+
/** One slot as read from the relay. */
|
|
336
|
+
export interface SlotBlob {
|
|
337
|
+
dTag: string
|
|
338
|
+
eventId: string
|
|
339
|
+
createdAt: number
|
|
340
|
+
blob: ReadStateBlob
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Every slot merged by the max rule, capped at {@link MAX_CONTEXTS} newest first, ties by key. */
|
|
344
|
+
export function mergeSlots(slots: readonly Pick<SlotBlob, 'blob'>[]): Record<string, number> {
|
|
345
|
+
const merged: Record<string, number> = {}
|
|
346
|
+
for (const { blob } of slots) {
|
|
347
|
+
for (const [id, seconds] of Object.entries(blob.contexts)) {
|
|
348
|
+
if (!isPublishableContextId(id) || !isTimestamp(seconds)) continue
|
|
349
|
+
if (merged[id] === undefined || seconds > merged[id]) merged[id] = seconds
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
const keys = Object.keys(merged)
|
|
353
|
+
if (keys.length <= MAX_CONTEXTS) return merged
|
|
354
|
+
const kept: Record<string, number> = {}
|
|
355
|
+
for (const id of keys.sort(byNewestThenKey(merged)).slice(0, MAX_CONTEXTS)) kept[id] = merged[id]
|
|
356
|
+
return kept
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Which slots are this installation's. */
|
|
360
|
+
export interface OwnSlotVerdict {
|
|
361
|
+
/** Our newest slot by `client_id`. */
|
|
362
|
+
mine: SlotBlob | undefined
|
|
363
|
+
/** Older slots under our `client_id` — left by a rotation. */
|
|
364
|
+
staleDuplicates: SlotBlob[]
|
|
365
|
+
/** Our coordinate holds another installation's `client_id`: rotate before writing. */
|
|
366
|
+
coordinateConflicted: boolean
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function classifyOwnSlots(slots: readonly SlotBlob[], identity: SlotIdentity): OwnSlotVerdict {
|
|
370
|
+
const ownDTag = readStateDTag(identity.slotId)
|
|
371
|
+
const [mine, ...staleDuplicates] = slots.filter((s) => s.blob.client_id === identity.clientId).sort((a, b) => b.createdAt - a.createdAt)
|
|
372
|
+
const atOwn = slots.find((s) => s.dTag === ownDTag)
|
|
373
|
+
return { mine, staleDuplicates, coordinateConflicted: atOwn !== undefined && atOwn.blob.client_id !== identity.clientId }
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* The effective marker (§11.3): the later of a context's own and its stream's.
|
|
378
|
+
* For a reply, `context` is `thread:<root>` and `stream` the file address or
|
|
379
|
+
* channel uuid. The channel never reaches into a file's stream — pass the
|
|
380
|
+
* file's address, not the channel, for a file's thread.
|
|
381
|
+
*/
|
|
382
|
+
export function effectiveReadAt(merged: Readonly<Record<string, number>>, context: string, stream?: string): number | undefined {
|
|
383
|
+
const own = merged[context]
|
|
384
|
+
const parent = stream === undefined ? undefined : merged[stream]
|
|
385
|
+
if (own === undefined) return parent
|
|
386
|
+
if (parent === undefined) return own
|
|
387
|
+
return Math.max(own, parent)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// ── The relay — injected ────────────────────────────────────────────────────
|
|
391
|
+
|
|
392
|
+
/** NIP-44 to self. Estiva apps hold no key, so this is a round trip to the identity service. */
|
|
393
|
+
export interface Nip44 {
|
|
394
|
+
encrypt(plaintext: string): Promise<string>
|
|
395
|
+
/** Undefined, or a throw, when it will not decrypt. */
|
|
396
|
+
decrypt(ciphertext: string): Promise<string | undefined>
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Read state as far as the relay can tell. */
|
|
400
|
+
export interface FetchedReadState {
|
|
401
|
+
/** False when the relay could not be asked — not the same as "no slots". */
|
|
402
|
+
reachable: boolean
|
|
403
|
+
merged: Record<string, number>
|
|
404
|
+
slots: SlotBlob[]
|
|
405
|
+
/** This installation's own blob, when the relay holds one at our coordinate and it decrypted. */
|
|
406
|
+
own?: ReadStateBlob
|
|
407
|
+
/**
|
|
408
|
+
* Our coordinate exists and would not decrypt — typically a `429` from
|
|
409
|
+
* `/nip44/decrypt`. Publishing now would replace it with only this session's
|
|
410
|
+
* markers, so an app must not.
|
|
411
|
+
*/
|
|
412
|
+
ownUndecryptable: boolean
|
|
413
|
+
/** Our coordinate holds another installation's blob: {@link rotateSlotId} before writing. */
|
|
414
|
+
coordinateConflicted: boolean
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Fetch every slot within the horizon, decrypt what decrypts, merge. */
|
|
418
|
+
export async function fetchReadState(
|
|
419
|
+
query: QueryFn,
|
|
420
|
+
pubkey: string,
|
|
421
|
+
nip44: Pick<Nip44, 'decrypt'>,
|
|
422
|
+
identity: SlotIdentity,
|
|
423
|
+
nowMs: number,
|
|
424
|
+
horizonDays: number = READ_STATE_HORIZON_DAYS,
|
|
425
|
+
): Promise<FetchedReadState> {
|
|
426
|
+
let events: SignedEvent[]
|
|
427
|
+
try {
|
|
428
|
+
events = await query([allSlotsFilter(pubkey, nowMs, horizonDays)])
|
|
429
|
+
} catch {
|
|
430
|
+
return { reachable: false, merged: {}, slots: [], ownUndecryptable: false, coordinateConflicted: false }
|
|
431
|
+
}
|
|
432
|
+
const ownDTag = readStateDTag(identity.slotId)
|
|
433
|
+
const slots: SlotBlob[] = []
|
|
434
|
+
let ownUndecryptable = false
|
|
435
|
+
for (const event of events) {
|
|
436
|
+
if (event.pubkey !== pubkey || event.kind !== KIND_APP_DATA) continue
|
|
437
|
+
const dTag = event.tags.find((t) => t[0] === 'd')?.[1]
|
|
438
|
+
if (!dTag?.startsWith(READ_STATE_D_PREFIX)) continue
|
|
439
|
+
let plaintext: string | undefined
|
|
440
|
+
// One at a time on purpose: `/nip44/decrypt` answers 429 to a burst, and
|
|
441
|
+
// a 429 on our own slot reads as undecryptable and blocks publishing.
|
|
442
|
+
try {
|
|
443
|
+
plaintext = await nip44.decrypt(event.content)
|
|
444
|
+
} catch {
|
|
445
|
+
plaintext = undefined
|
|
446
|
+
}
|
|
447
|
+
const blob = parseReadStateBlob(plaintext)
|
|
448
|
+
if (!blob) {
|
|
449
|
+
// Another slot that will not decrypt belongs to a rotated key: skipped.
|
|
450
|
+
if (dTag === ownDTag) ownUndecryptable = true
|
|
451
|
+
continue
|
|
452
|
+
}
|
|
453
|
+
slots.push({ dTag, eventId: event.id, createdAt: event.created_at, blob })
|
|
454
|
+
}
|
|
455
|
+
const atOwn = slots.find((s) => s.dTag === ownDTag)
|
|
456
|
+
const coordinateConflicted = atOwn !== undefined && atOwn.blob.client_id !== identity.clientId
|
|
457
|
+
return {
|
|
458
|
+
reachable: true,
|
|
459
|
+
merged: mergeSlots(slots),
|
|
460
|
+
slots,
|
|
461
|
+
own: atOwn && !coordinateConflicted ? atOwn.blob : undefined,
|
|
462
|
+
ownUndecryptable,
|
|
463
|
+
coordinateConflicted,
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Encrypt, sign and publish this slot's whole blob. The caller has already capped `contexts`. */
|
|
468
|
+
export async function publishReadState(
|
|
469
|
+
deps: {
|
|
470
|
+
sign: (event: UnsignedEvent) => Promise<SignedEvent>
|
|
471
|
+
publish: (event: SignedEvent) => Promise<{ ok: boolean; reason?: string }>
|
|
472
|
+
nip44: Pick<Nip44, 'encrypt'>
|
|
473
|
+
},
|
|
474
|
+
pubkey: string,
|
|
475
|
+
identity: SlotIdentity,
|
|
476
|
+
contexts: Readonly<Record<string, number>>,
|
|
477
|
+
nowMs: number,
|
|
478
|
+
): Promise<{ ok: boolean; reason?: string }> {
|
|
479
|
+
// Filtered here as well: the blob is grow-only, and a map built outside `advanceContexts` must not put an id into it.
|
|
480
|
+
const plaintext = serializeReadStateBlob({ v: 1, client_id: identity.clientId, contexts: advanceContexts({}, contexts).contexts })
|
|
481
|
+
if (utf8(plaintext) > MAX_BLOB_BYTES) return { ok: false, reason: `read state is ${utf8(plaintext)} bytes, over ${MAX_BLOB_BYTES}` }
|
|
482
|
+
const ciphertext = await deps.nip44.encrypt(plaintext)
|
|
483
|
+
const signed = await deps.sign(buildReadStateEvent(pubkey, nowMs, identity.slotId, ciphertext))
|
|
484
|
+
const result = await deps.publish(signed)
|
|
485
|
+
return { ok: result.ok, reason: result.reason }
|
|
486
|
+
}
|
package/src/strength.ts
CHANGED
|
@@ -155,8 +155,8 @@ export function referenceTagsFor(body: string, own = ''): NostrTag[] {
|
|
|
155
155
|
/** The most `p` tags a message carries — Buzz's cap, and `buildMessage`'s. */
|
|
156
156
|
export const MAX_MENTIONED_PEOPLE = 50
|
|
157
157
|
|
|
158
|
-
/** The people a body mentions by `nostr:npub
|
|
159
|
-
export function
|
|
158
|
+
/** The people a body mentions by `nostr:npub…` (§13.1), in the order it names them. */
|
|
159
|
+
export function peopleNamedInBody(body: string): Set<string> {
|
|
160
160
|
const pubkeys = new Set<string>()
|
|
161
161
|
for (const uri of findNostrUris(body)) {
|
|
162
162
|
if (!/^nostr:npub1/i.test(uri)) continue
|
|
@@ -166,5 +166,10 @@ export function mentionTagsFor(body: string): NostrTag[] {
|
|
|
166
166
|
// A malformed key is prose.
|
|
167
167
|
}
|
|
168
168
|
}
|
|
169
|
-
return
|
|
169
|
+
return pubkeys
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The people a body mentions by `nostr:npub…`, as `p` tags, capped at {@link MAX_MENTIONED_PEOPLE}. */
|
|
173
|
+
export function mentionTagsFor(body: string): NostrTag[] {
|
|
174
|
+
return [...peopleNamedInBody(body)].slice(0, MAX_MENTIONED_PEOPLE).map((p) => ['p', p])
|
|
170
175
|
}
|
package/src/unread.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What is unread — SPEC §11.8 *What membership changes about unread*, judged
|
|
3
|
+
* against §11.3's effective marker.
|
|
4
|
+
*
|
|
5
|
+
* A message in a stream is unread for `P` when all of these hold:
|
|
6
|
+
*
|
|
7
|
+
* 1. `P` is a member and has not muted the stream, or its content mentions `P`;
|
|
8
|
+
* 2. `P` did not write it;
|
|
9
|
+
* 3. its `created_at` is at or after the second `P` became a member;
|
|
10
|
+
* 4. it is newer than `P`'s effective marker.
|
|
11
|
+
*
|
|
12
|
+
* For a file, membership is {@link membershipOf}'s fold, and condition 3 is
|
|
13
|
+
* what settles a file with no marker (§11.6): unread from joining, not from
|
|
14
|
+
* the start of a horizon. A channel's general stream takes its membership
|
|
15
|
+
* from the roster, which carries no join time — so `since` is undefined and
|
|
16
|
+
* what counts without a marker is the app's `floor`.
|
|
17
|
+
*
|
|
18
|
+
* An app lights nothing for a stream it has no screen for (§11.8); that is
|
|
19
|
+
* the caller's to decide by not asking.
|
|
20
|
+
*/
|
|
21
|
+
import type { SignedEvent } from '@estiva-app/protocol'
|
|
22
|
+
import { effectiveReadAt, threadContext } from './readState.js'
|
|
23
|
+
import { peopleNamedInBody } from './strength.js'
|
|
24
|
+
import { groupThreads } from './threads.js'
|
|
25
|
+
|
|
26
|
+
type Message = Pick<SignedEvent, 'id' | 'pubkey' | 'kind' | 'created_at' | 'tags' | 'content'>
|
|
27
|
+
|
|
28
|
+
/** Who is judging one stream, and on what terms. */
|
|
29
|
+
export interface StreamJudge {
|
|
30
|
+
/** The stream's context (§11.1): the file's address, or the channel uuid for its general stream. */
|
|
31
|
+
stream: string
|
|
32
|
+
/** The person reading. */
|
|
33
|
+
me: string
|
|
34
|
+
/** Whether `me` is a member — {@link membershipOf} for a file, the roster for a channel. */
|
|
35
|
+
member: boolean
|
|
36
|
+
/** Unix seconds `me` became a member; undefined for a channel, where the roster has no join time. */
|
|
37
|
+
since?: number
|
|
38
|
+
/** Whether `me` muted the stream (`estiva:muted:v1`). A mention still counts. */
|
|
39
|
+
muted?: boolean
|
|
40
|
+
/**
|
|
41
|
+
* For a stream with no marker, the earliest `created_at` that counts — the
|
|
42
|
+
* app's choice for a channel (§11.6). A file member does not need it: `since`
|
|
43
|
+
* already bounds it. Undefined counts everything.
|
|
44
|
+
*/
|
|
45
|
+
floor?: number
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The unread messages of one stream, oldest first per thread. `messages` is
|
|
50
|
+
* the stream's own (see {@link streamOf} for a file); a reply is judged
|
|
51
|
+
* against `thread:<root>` as well as the stream (§11.3).
|
|
52
|
+
*
|
|
53
|
+
* A dot is `unreadIn(…).length > 0`; a divider goes above the first unread
|
|
54
|
+
* message of each thread.
|
|
55
|
+
*/
|
|
56
|
+
export function unreadIn<E extends Message>(messages: readonly E[], merged: Readonly<Record<string, number>>, judge: StreamJudge): E[] {
|
|
57
|
+
const { roots, replies } = groupThreads(messages)
|
|
58
|
+
const out: E[] = []
|
|
59
|
+
const consider = (message: E, root: string | undefined) => {
|
|
60
|
+
if (isUnread(message, root, merged, judge)) out.push(message)
|
|
61
|
+
}
|
|
62
|
+
for (const root of roots) {
|
|
63
|
+
consider(root, undefined)
|
|
64
|
+
for (const reply of replies[root.id] ?? []) consider(reply, root.id)
|
|
65
|
+
}
|
|
66
|
+
const held = new Set(roots.map((r) => r.id))
|
|
67
|
+
for (const [root, list] of Object.entries(replies)) {
|
|
68
|
+
if (held.has(root)) continue
|
|
69
|
+
for (const reply of list) consider(reply, root)
|
|
70
|
+
}
|
|
71
|
+
return out
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Whether one message is unread: §11.8's four conditions. `root` is its thread's root id when it is a reply. */
|
|
75
|
+
export function isUnread(message: Message, root: string | undefined, merged: Readonly<Record<string, number>>, judge: StreamJudge): boolean {
|
|
76
|
+
if (message.pubkey === judge.me) return false
|
|
77
|
+
const mentioned = peopleNamedInBody(message.content).has(judge.me)
|
|
78
|
+
if (!mentioned && (!judge.member || judge.muted)) return false
|
|
79
|
+
if (judge.since !== undefined && message.created_at < judge.since) return false
|
|
80
|
+
const thread = root === undefined ? undefined : threadContext(root)
|
|
81
|
+
const marker = thread === undefined ? merged[judge.stream] : effectiveReadAt(merged, thread, judge.stream)
|
|
82
|
+
if (marker !== undefined) return message.created_at > marker
|
|
83
|
+
if (judge.since !== undefined) return true
|
|
84
|
+
return judge.floor === undefined || message.created_at >= judge.floor
|
|
85
|
+
}
|