signet-protocol 1.10.1 → 1.11.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/dist/bot-ownership.d.ts +61 -0
- package/dist/bot-ownership.d.ts.map +1 -0
- package/dist/bot-ownership.js +88 -0
- package/dist/bot-ownership.js.map +1 -0
- package/dist/crypto.d.ts +2 -0
- package/dist/crypto.d.ts.map +1 -1
- package/dist/crypto.js +4 -0
- package/dist/crypto.js.map +1 -1
- package/dist/experimental.d.ts +19 -0
- package/dist/experimental.d.ts.map +1 -0
- package/dist/experimental.js +16 -0
- package/dist/experimental.js.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/url-auth.d.ts.map +1 -1
- package/dist/url-auth.js +2 -1
- package/dist/url-auth.js.map +1 -1
- package/dist/utils.d.ts +46 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +127 -0
- package/dist/utils.js.map +1 -1
- package/dist/vault-checkpoint.d.ts +50 -0
- package/dist/vault-checkpoint.d.ts.map +1 -0
- package/dist/vault-checkpoint.js +84 -0
- package/dist/vault-checkpoint.js.map +1 -0
- package/dist/vault-keys.d.ts +19 -0
- package/dist/vault-keys.d.ts.map +1 -0
- package/dist/vault-keys.js +57 -0
- package/dist/vault-keys.js.map +1 -0
- package/dist/vault-recovery.d.ts +99 -0
- package/dist/vault-recovery.d.ts.map +1 -0
- package/dist/vault-recovery.js +305 -0
- package/dist/vault-recovery.js.map +1 -0
- package/dist/vault-relay.d.ts +29 -0
- package/dist/vault-relay.d.ts.map +1 -0
- package/dist/vault-relay.js +131 -0
- package/dist/vault-relay.js.map +1 -0
- package/package.json +8 -4
- package/src/bot-ownership.ts +77 -0
- package/src/crypto.ts +5 -0
- package/src/experimental.ts +25 -0
- package/src/index.ts +3 -0
- package/src/url-auth.ts +2 -1
- package/src/utils.ts +122 -0
- package/src/vault-checkpoint.ts +98 -0
- package/src/vault-keys.ts +59 -0
- package/src/vault-recovery.ts +284 -0
- package/src/vault-relay.ts +112 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import type { NostrEvent } from './types.js'
|
|
2
|
+
import { verifyEvent } from './crypto.js'
|
|
3
|
+
import { MAX_VAULT_CHUNKS, MAX_VAULT_CONTROL_BYTES, VAULT_EVENT_KIND,
|
|
4
|
+
matchesVaultChunk, parseVaultCheckpoint, vaultCheckpointShapedTag, vaultCheckpointTag, vaultContentHash } from './vault-checkpoint.js'
|
|
5
|
+
import type { VaultCheckpoint } from './vault-checkpoint.js'
|
|
6
|
+
|
|
7
|
+
/** A checkpoint dated further than this beyond the reader's clock is rejected,
|
|
8
|
+
* so one device with a bad clock cannot outrank every later honest head. */
|
|
9
|
+
export const VAULT_CLOCK_TOLERANCE_SECONDS = 300
|
|
10
|
+
const MAX_VAULT_HEADS = 16
|
|
11
|
+
/** Rotations recovery will walk. A vault rotated more than 32 times reads
|
|
12
|
+
* `unusable`; there is no way past it without raising this bound. */
|
|
13
|
+
const MAX_ROTATION_HOPS = 32
|
|
14
|
+
const encoder = new TextEncoder()
|
|
15
|
+
const nowSeconds = () => Math.floor(Date.now() / 1000)
|
|
16
|
+
type Ready = Extract<VaultReadResult, { state: 'ready' }>
|
|
17
|
+
|
|
18
|
+
type Unavailable = Extract<VaultReadResult, { state: 'unavailable' }>
|
|
19
|
+
/** Carry the failed relay list from a `VaultRelayError` (or any error with a
|
|
20
|
+
* string-array `failedRelays`) into the result. */
|
|
21
|
+
function unavailable(error?: unknown): Unavailable {
|
|
22
|
+
const failed = (error as { failedRelays?: unknown } | undefined)?.failedRelays
|
|
23
|
+
return Array.isArray(failed) && failed.every(f => typeof f === 'string')
|
|
24
|
+
? { state: 'unavailable', failedRelays: [...failed] } : { state: 'unavailable' }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function checkNow(now: number): number {
|
|
28
|
+
if (!Number.isSafeInteger(now) || now < 0) throw new Error('Vault reader clock must be a non-negative integer')
|
|
29
|
+
return now
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function checkMinRotation(minRotation: number): number {
|
|
33
|
+
if (!Number.isSafeInteger(minRotation) || minRotation < 0) {
|
|
34
|
+
throw new Error('Vault reader minRotation must be a non-negative integer')
|
|
35
|
+
}
|
|
36
|
+
return minRotation
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The highest rotation number a caller's floors already name, ignoring any
|
|
40
|
+
* non-integer or negative key. -1 when `floors` names none, so a rotation-0
|
|
41
|
+
* result is never treated as a rollback when nothing has been seen yet. */
|
|
42
|
+
function highestFloorRotation(floors: Readonly<Record<number, number>>): number {
|
|
43
|
+
let highest = -1
|
|
44
|
+
for (const key of Object.keys(floors)) {
|
|
45
|
+
const rotation = Number(key)
|
|
46
|
+
if (Number.isInteger(rotation) && rotation >= 0 && rotation > highest) highest = rotation
|
|
47
|
+
}
|
|
48
|
+
return highest
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Ascending (created_at, id): the order used for every newest/tie decision.
|
|
52
|
+
* Of two events with the same created_at, the lower ID is the newer head,
|
|
53
|
+
* matching NIP-01 replaceable-event resolution. */
|
|
54
|
+
const older = (a: NostrEvent, b: NostrEvent) => a.created_at - b.created_at || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)
|
|
55
|
+
|
|
56
|
+
/** Structural, bound and signature checks shared by every checkpoint read. */
|
|
57
|
+
async function authenticCheckpointEvent(event: NostrEvent, author: string, now: number): Promise<string | null> {
|
|
58
|
+
if (!event || event.kind !== VAULT_EVENT_KIND || event.pubkey !== author || typeof event.id !== 'string'
|
|
59
|
+
|| typeof event.content !== 'string' || encoder.encode(event.content).length > MAX_VAULT_CONTROL_BYTES
|
|
60
|
+
|| !Number.isSafeInteger(event.created_at) || event.created_at < 0
|
|
61
|
+
|| event.created_at > now + VAULT_CLOCK_TOLERANCE_SECONDS) return null
|
|
62
|
+
const tag = vaultCheckpointShapedTag(event)
|
|
63
|
+
return tag !== null && await verifyEvent(event) ? tag : null
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type VaultReadResult =
|
|
67
|
+
| { state: 'absent' }
|
|
68
|
+
/** `failedRelays`, when known, names the relays that did not answer. */
|
|
69
|
+
| { state: 'unavailable'; failedRelays?: string[] }
|
|
70
|
+
| { state: 'unusable'; reason: 'checkpoint' | 'rollback' | 'chunk' | 'revision' }
|
|
71
|
+
| { state: 'ready'; plaintext: string; checkpoint: VaultCheckpoint; event: NostrEvent }
|
|
72
|
+
|
|
73
|
+
export interface VaultReader {
|
|
74
|
+
/** Must distinguish an empty reachable query from relay failure (throw).
|
|
75
|
+
* An error carrying `failedRelays: string[]` is reported in the result. */
|
|
76
|
+
checkpoints(author: string, dTag?: string): Promise<NostrEvent[]>
|
|
77
|
+
/** Exact ID query. Missing data is a failed restore, never an empty dataset. */
|
|
78
|
+
chunk(eventId: string): Promise<NostrEvent | null>
|
|
79
|
+
/** Open the v2 envelope only; sender is the vault key, not the chunk signer. */
|
|
80
|
+
open(content: string, vaultAuthor: string): Promise<string | null>
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Read one rotation. Callers may fall back to legacy ONLY on `absent`.
|
|
84
|
+
* Invalid, incomplete, offline and rolled-back backups are distinguishable from
|
|
85
|
+
* never-migrated accounts. No state is persisted or marked canonical here.
|
|
86
|
+
* `now` (unix seconds, default the local clock) bounds created_at from above.
|
|
87
|
+
*/
|
|
88
|
+
export async function readVaultSnapshot(
|
|
89
|
+
reader: VaultReader,
|
|
90
|
+
expected: { author: string; purpose: string; rotation: number; minSequence?: number; publisher?: string; now?: number },
|
|
91
|
+
): Promise<VaultReadResult> {
|
|
92
|
+
const now = checkNow(expected.now ?? nowSeconds())
|
|
93
|
+
const tag = vaultCheckpointTag(expected.author, expected.publisher)
|
|
94
|
+
let candidates: NostrEvent[]
|
|
95
|
+
try { candidates = await reader.checkpoints(expected.author, tag) } catch (e) { return unavailable(e) }
|
|
96
|
+
if (!candidates.length) return { state: 'absent' }
|
|
97
|
+
if (candidates.length > 128) return { state: 'unusable', reason: 'checkpoint' }
|
|
98
|
+
// A corrupt newer event does not hide a valid older event. Once a valid signed
|
|
99
|
+
// event is chosen, however, failed decrypt/schema is not a licence to downgrade.
|
|
100
|
+
const valid: NostrEvent[] = []
|
|
101
|
+
for (const event of candidates) {
|
|
102
|
+
if (await authenticCheckpointEvent(event, expected.author, now) === tag) valid.push(event)
|
|
103
|
+
}
|
|
104
|
+
valid.sort((a, b) => older(b, a))
|
|
105
|
+
const event = valid[0]
|
|
106
|
+
if (!event) return { state: 'unusable', reason: 'checkpoint' }
|
|
107
|
+
let raw: string | null
|
|
108
|
+
try { raw = await reader.open(event.content, expected.author) } catch { return { state: 'unusable', reason: 'checkpoint' } }
|
|
109
|
+
const checkpoint = raw === null ? null : parseVaultCheckpoint(raw, expected)
|
|
110
|
+
if (!checkpoint || checkpoint.publisher !== expected.publisher) return { state: 'unusable', reason: 'checkpoint' }
|
|
111
|
+
if (checkpoint.sequence < (expected.minSequence ?? 0)) return { state: 'unusable', reason: 'rollback' }
|
|
112
|
+
const parts: string[] = []
|
|
113
|
+
let totalBytes = 0
|
|
114
|
+
for (const ref of checkpoint.chunks) {
|
|
115
|
+
let chunk: NostrEvent | null
|
|
116
|
+
try { chunk = await reader.chunk(ref.eventId) } catch (e) { return unavailable(e) }
|
|
117
|
+
if (!chunk || typeof chunk.content !== 'string' || !matchesVaultChunk(ref, chunk) || !await verifyEvent(chunk)) {
|
|
118
|
+
return { state: 'unusable', reason: 'chunk' }
|
|
119
|
+
}
|
|
120
|
+
let part: string | null
|
|
121
|
+
try { part = await reader.open(chunk.content, expected.author) } catch { return { state: 'unusable', reason: 'chunk' } }
|
|
122
|
+
if (part === null) return { state: 'unusable', reason: 'chunk' }
|
|
123
|
+
totalBytes += encoder.encode(part).length
|
|
124
|
+
if (totalBytes > MAX_VAULT_CHUNKS * 65536) return { state: 'unusable', reason: 'chunk' }
|
|
125
|
+
parts.push(part)
|
|
126
|
+
}
|
|
127
|
+
const plaintext = parts.join('')
|
|
128
|
+
if (vaultContentHash(plaintext) !== checkpoint.revision) return { state: 'unusable', reason: 'revision' }
|
|
129
|
+
return { state: 'ready', plaintext, checkpoint, event }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Whether a rotation holds any authentic checkpoint-shaped event (optionally
|
|
133
|
+
* under one exact tag). Contents are never opened, so nothing written under a
|
|
134
|
+
* superseded key is decrypted, parsed or counted. */
|
|
135
|
+
async function rotationPresent(reader: VaultReader, author: string, now: number, tag?: string):
|
|
136
|
+
Promise<'present' | 'absent' | Unavailable> {
|
|
137
|
+
let events: NostrEvent[]
|
|
138
|
+
try { events = await reader.checkpoints(author, tag) } catch (e) { return unavailable(e) }
|
|
139
|
+
for (const event of events.slice(0, 1024)) {
|
|
140
|
+
const found = await authenticCheckpointEvent(event, author, now)
|
|
141
|
+
if (found !== null && (tag === undefined || found === tag)) return 'present'
|
|
142
|
+
}
|
|
143
|
+
return 'absent'
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Find the newest rotation: the first rotation whose successor holds no
|
|
147
|
+
* authentic checkpoint. Rotation is a revocation boundary: once rotation n + 1
|
|
148
|
+
* exists, rotation n is never read (only rotation n + 1's key can sign there),
|
|
149
|
+
* so a holder of a retired key can neither inject heads nor block recovery by
|
|
150
|
+
* writing to the old rotation, and cannot hide the successor by overwriting
|
|
151
|
+
* the pointer. Costs one extra resolve and query for the successor.
|
|
152
|
+
*
|
|
153
|
+
* A rotation revokes only a holder of THAT rotation's key, not the tree root:
|
|
154
|
+
* a holder of the root key can derive every rotation regardless, so rotation
|
|
155
|
+
* is a boundary against a retired per-rotation key, not against root
|
|
156
|
+
* compromise. This walk can find a rotation older than one a caller has
|
|
157
|
+
* already read (every relay withholding the successor); callers that track
|
|
158
|
+
* the highest rotation they have seen must reject a lower result as a
|
|
159
|
+
* rollback rather than trust it, since "not found" here never means "does
|
|
160
|
+
* not exist". */
|
|
161
|
+
async function newestRotation<C extends { reader: VaultReader; author: string }>(
|
|
162
|
+
resolve: (rotation: number) => Promise<C>, now: number, tagFor?: (author: string) => string,
|
|
163
|
+
): Promise<{ rotation: number; context: C } | Exclude<VaultReadResult, { state: 'ready' }>> {
|
|
164
|
+
let rotation = 0
|
|
165
|
+
let context: C
|
|
166
|
+
try { context = await resolve(0) } catch (e) { return unavailable(e) }
|
|
167
|
+
for (let hop = 0; hop < MAX_ROTATION_HOPS; hop++) {
|
|
168
|
+
let next: C
|
|
169
|
+
try { next = await resolve(rotation + 1) } catch (e) { return unavailable(e) }
|
|
170
|
+
const probe = await rotationPresent(next.reader, next.author, now, tagFor?.(next.author))
|
|
171
|
+
if (probe === 'absent') return { rotation, context }
|
|
172
|
+
if (probe !== 'present') return probe
|
|
173
|
+
rotation++
|
|
174
|
+
context = next
|
|
175
|
+
}
|
|
176
|
+
return { state: 'unusable', reason: 'checkpoint' }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Read the newest rotation's legacy (publisher-less) checkpoint. Rotations are
|
|
180
|
+
* contiguous from zero; see `newestRotation` for the revocation boundary. A
|
|
181
|
+
* `nextRotation` pointer (always rotation + 1) to a rotation with no authentic
|
|
182
|
+
* checkpoint is damage, not a never-migrated account.
|
|
183
|
+
*
|
|
184
|
+
* Any key present in `floors`, whatever its value (including 0), counts as a
|
|
185
|
+
* rotation this caller has already reached: the walk refuses to land below
|
|
186
|
+
* the highest such key. Callers must not pre-fill a floor for a rotation they
|
|
187
|
+
* have not actually reached, or a legitimate read of that rotation would be
|
|
188
|
+
* refused as a rollback.
|
|
189
|
+
*/
|
|
190
|
+
export async function readVaultRotations(
|
|
191
|
+
resolve: (rotation: number) => Promise<{ reader: VaultReader; author: string }>,
|
|
192
|
+
purpose: string,
|
|
193
|
+
floors: Readonly<Record<number, number>> = {},
|
|
194
|
+
now: number = nowSeconds(),
|
|
195
|
+
): Promise<VaultReadResult> {
|
|
196
|
+
checkNow(now)
|
|
197
|
+
const found = await newestRotation(resolve, now, author => vaultCheckpointTag(author))
|
|
198
|
+
if (!('context' in found)) return found
|
|
199
|
+
const { rotation, context } = found
|
|
200
|
+
if (rotation < highestFloorRotation(floors)) return { state: 'unusable', reason: 'rollback' }
|
|
201
|
+
const result = await readVaultSnapshot(context.reader, {
|
|
202
|
+
author: context.author, purpose, rotation, minSequence: floors[rotation], now,
|
|
203
|
+
})
|
|
204
|
+
if (result.state === 'absent') return rotation > 0 ? { state: 'unusable', reason: 'checkpoint' } : result
|
|
205
|
+
if (result.state === 'ready' && result.checkpoint.nextRotation !== undefined) return { state: 'unusable', reason: 'checkpoint' }
|
|
206
|
+
return result
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export type VaultHeadsResult = Exclude<VaultReadResult, { state: 'ready' }>
|
|
210
|
+
| { state: 'ready'; snapshots: Ready[] }
|
|
211
|
+
|
|
212
|
+
interface HeadsExpected {
|
|
213
|
+
author: string; purpose: string; rotation: number; sequenceFloors?: Readonly<Record<string, number>>; now?: number
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Mergeable per-device heads prevent last-writer replacement across devices.
|
|
217
|
+
* Discovery queries only the private vault author. No device roster is public.
|
|
218
|
+
* Reads one rotation strictly: events without a checkpoint-shaped d-tag are
|
|
219
|
+
* ignored, then every remaining head must be valid, and more than 16 fails.
|
|
220
|
+
*/
|
|
221
|
+
export async function readVaultHeads(reader: VaultReader, expected: HeadsExpected): Promise<VaultHeadsResult> {
|
|
222
|
+
const now = checkNow(expected.now ?? nowSeconds())
|
|
223
|
+
let events: NostrEvent[]
|
|
224
|
+
try { events = await reader.checkpoints(expected.author) } catch (e) { return unavailable(e) }
|
|
225
|
+
const shaped = events.filter(e => !!e && e.pubkey === expected.author && e.kind === VAULT_EVENT_KIND
|
|
226
|
+
&& vaultCheckpointShapedTag(e) !== null)
|
|
227
|
+
if (!shaped.length) return { state: 'absent' }
|
|
228
|
+
if (shaped.length > 128) return { state: 'unusable', reason: 'checkpoint' }
|
|
229
|
+
const heads = new Map<string, NostrEvent>()
|
|
230
|
+
for (const event of shaped) {
|
|
231
|
+
const tag = await authenticCheckpointEvent(event, expected.author, now)
|
|
232
|
+
if (tag === null) continue
|
|
233
|
+
const previous = heads.get(tag)
|
|
234
|
+
if (!previous || older(previous, event) < 0) heads.set(tag, event)
|
|
235
|
+
}
|
|
236
|
+
if (!heads.size || heads.size > MAX_VAULT_HEADS) return { state: 'unusable', reason: 'checkpoint' }
|
|
237
|
+
const snapshots: Ready[] = []
|
|
238
|
+
for (const [tag, event] of heads) {
|
|
239
|
+
let raw: string | null
|
|
240
|
+
try { raw = await reader.open(event.content, expected.author) } catch { return { state: 'unusable', reason: 'checkpoint' } }
|
|
241
|
+
const checkpoint = raw === null ? null : parseVaultCheckpoint(raw, expected)
|
|
242
|
+
if (!checkpoint || tag !== vaultCheckpointTag(expected.author, checkpoint.publisher)) return { state: 'unusable', reason: 'checkpoint' }
|
|
243
|
+
const result = await readVaultSnapshot({ ...reader, checkpoints: async () => [event],
|
|
244
|
+
open: (content, author) => content === event.content ? Promise.resolve(raw) : reader.open(content, author),
|
|
245
|
+
}, { author: expected.author, purpose: expected.purpose, rotation: expected.rotation, now,
|
|
246
|
+
publisher: checkpoint.publisher, minSequence: expected.sequenceFloors?.[checkpoint.publisher ?? 'legacy'] })
|
|
247
|
+
if (result.state !== 'ready') return result
|
|
248
|
+
snapshots.push(result)
|
|
249
|
+
}
|
|
250
|
+
for (const [publisher, floor] of Object.entries(expected.sequenceFloors ?? {})) {
|
|
251
|
+
if (floor > 0 && !snapshots.some(s => (s.checkpoint.publisher ?? 'legacy') === publisher)) return { state: 'unusable', reason: 'rollback' }
|
|
252
|
+
}
|
|
253
|
+
snapshots.sort((a, b) => older(a.event, b.event))
|
|
254
|
+
return { state: 'ready', snapshots }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Read the newest rotation's merged per-device heads. Rotation is a
|
|
258
|
+
* revocation boundary (see `newestRotation`): heads of a superseded rotation
|
|
259
|
+
* are never merged, opened or counted, so the rotating writer must carry every
|
|
260
|
+
* head's state into the new rotation before publishing there. Floors from
|
|
261
|
+
* `resolve` apply to the rotation that is read.
|
|
262
|
+
*
|
|
263
|
+
* `minRotation` is the highest rotation this caller has already reached. If
|
|
264
|
+
* every relay withholds the true newest rotation's successor, `newestRotation`
|
|
265
|
+
* cannot distinguish that from a vault that never rotated further, and would
|
|
266
|
+
* otherwise report a lower rotation's heads as `ready`; a caller-tracked floor
|
|
267
|
+
* on the walk itself is what catches that withholding.
|
|
268
|
+
*/
|
|
269
|
+
export async function readVaultHeadRotations(resolve: (rotation: number) => Promise<{
|
|
270
|
+
reader: VaultReader; author: string; sequenceFloors?: Readonly<Record<string, number>>;
|
|
271
|
+
}>, purpose: string, now: number = nowSeconds(), minRotation = 0): Promise<VaultHeadsResult> {
|
|
272
|
+
checkNow(now)
|
|
273
|
+
checkMinRotation(minRotation)
|
|
274
|
+
const found = await newestRotation(resolve, now)
|
|
275
|
+
if (!('context' in found)) return found
|
|
276
|
+
const { rotation, context } = found
|
|
277
|
+
if (rotation < minRotation) return { state: 'unusable', reason: 'rollback' }
|
|
278
|
+
const result = await readVaultHeads(context.reader, { ...context, purpose, rotation, now })
|
|
279
|
+
if (result.state === 'absent') return rotation > 0 ? { state: 'unusable', reason: 'checkpoint' } : result
|
|
280
|
+
if (result.state === 'ready' && result.snapshots.some(s => s.checkpoint.nextRotation !== undefined)) {
|
|
281
|
+
return { state: 'unusable', reason: 'checkpoint' }
|
|
282
|
+
}
|
|
283
|
+
return result
|
|
284
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { RelayClient, type NostrFilter } from './relay.js'
|
|
2
|
+
import type { NostrEvent } from './types.js'
|
|
3
|
+
import type { VaultReader } from './vault-recovery.js'
|
|
4
|
+
import { VAULT_EVENT_KIND, vaultCheckpointShapedTag } from './vault-checkpoint.js'
|
|
5
|
+
|
|
6
|
+
/** Matching events one relay may contribute to one query. More fails that relay. */
|
|
7
|
+
export const MAX_VAULT_EVENTS_PER_RELAY = 128
|
|
8
|
+
const MAX_VAULT_RELAYS = 8
|
|
9
|
+
|
|
10
|
+
/** Must agree with the RelayClient constructor: a URL accepted here but rejected
|
|
11
|
+
* there would be skipped silently. Plain ws:// is loopback-only (localhost and
|
|
12
|
+
* 127.0.0.1; RelayClient does not accept [::1]). */
|
|
13
|
+
function validRelay(raw: string): boolean {
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(raw)
|
|
16
|
+
return !url.username && !url.password && !url.hash && (url.protocol === 'wss:'
|
|
17
|
+
|| (url.protocol === 'ws:' && ['localhost', '127.0.0.1'].includes(url.hostname)))
|
|
18
|
+
} catch { return false }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Client-side re-check of the relay filter. Relays are untrusted, so an event
|
|
22
|
+
* outside the requested author/kind/id/d-tag is dropped before it counts
|
|
23
|
+
* towards any limit. */
|
|
24
|
+
function matchesFilter(filter: NostrFilter, event: NostrEvent): boolean {
|
|
25
|
+
if (!event || typeof event.id !== 'string' || typeof event.pubkey !== 'string' || !Array.isArray(event.tags)) return false
|
|
26
|
+
if (filter.ids && !filter.ids.includes(event.id)) return false
|
|
27
|
+
if (filter.authors && !filter.authors.includes(event.pubkey)) return false
|
|
28
|
+
if (filter.kinds && !filter.kinds.includes(event.kind)) return false
|
|
29
|
+
const dTags = filter['#d']
|
|
30
|
+
if (dTags && !event.tags.some(t => Array.isArray(t) && t[0] === 'd' && dTags.includes(t[1]))) return false
|
|
31
|
+
return true
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A relay query that did not complete on every relay. `failedRelays` names the
|
|
35
|
+
* relays that errored, timed out or exceeded the cap. */
|
|
36
|
+
export class VaultRelayError extends Error {
|
|
37
|
+
constructor(message: string, readonly failedRelays: string[]) {
|
|
38
|
+
super(message)
|
|
39
|
+
this.name = 'VaultRelayError'
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** EOSE is required: a timed-out empty query is not evidence of absence.
|
|
44
|
+
* Events are filtered against `filter` (and `accept`, when given) and
|
|
45
|
+
* de-duplicated before the per-relay cap applies, so unrelated events cannot
|
|
46
|
+
* crowd out the requested ones. */
|
|
47
|
+
export function fetchVaultEvents(relay: Pick<RelayClient, 'subscribe' | 'closeSubscription'>,
|
|
48
|
+
filter: NostrFilter, timeoutMs = 10000, accept?: (event: NostrEvent) => boolean): Promise<NostrEvent[]> {
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
const events = new Map<string, NostrEvent>()
|
|
51
|
+
let subId: string | undefined
|
|
52
|
+
let finished = false
|
|
53
|
+
const finish = (error?: Error) => {
|
|
54
|
+
if (finished) return
|
|
55
|
+
finished = true
|
|
56
|
+
clearTimeout(timer)
|
|
57
|
+
if (subId) relay.closeSubscription(subId)
|
|
58
|
+
if (error) reject(error); else resolve([...events.values()])
|
|
59
|
+
}
|
|
60
|
+
const timer = setTimeout(() => finish(new Error('Vault query did not complete')), timeoutMs)
|
|
61
|
+
try {
|
|
62
|
+
subId = relay.subscribe([filter], event => {
|
|
63
|
+
if (finished || !matchesFilter(filter, event) || (accept && !accept(event)) || events.has(event.id)) return
|
|
64
|
+
if (events.size >= MAX_VAULT_EVENTS_PER_RELAY) finish(new Error('Vault query exceeds event limit'))
|
|
65
|
+
else events.set(event.id, event)
|
|
66
|
+
}, () => finish())
|
|
67
|
+
if (finished) relay.closeSubscription(subId)
|
|
68
|
+
} catch { finish(new Error('Vault query failed')) }
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Relay-backed reader. At most eight valid relay URLs are queried.
|
|
73
|
+
*
|
|
74
|
+
* A checkpoint query, empty or not, completes only when EVERY queried relay
|
|
75
|
+
* answered with EOSE: one relay's "nothing" is not evidence of absence, and one
|
|
76
|
+
* relay's heads may omit a device head another relay holds. Otherwise it throws
|
|
77
|
+
* a `VaultRelayError` naming the failed relays, and recovery reports
|
|
78
|
+
* `unavailable` with `failedRelays`. A permanently dead configured relay keeps
|
|
79
|
+
* reads unavailable until it is removed from the set. A chunk fetch by exact
|
|
80
|
+
* ID succeeds as soon as any relay returns it (its hash is pinned); "not found"
|
|
81
|
+
* again needs every relay. Checkpoint queries drop events without a
|
|
82
|
+
* checkpoint-shaped d-tag before the per-relay cap. */
|
|
83
|
+
export function createVaultRelayReader(relays: readonly string[], open: VaultReader['open']): VaultReader {
|
|
84
|
+
const urls = [...new Set(relays.filter(validRelay))].slice(0, MAX_VAULT_RELAYS)
|
|
85
|
+
const query = async (filter: NostrFilter, accept?: (event: NostrEvent) => boolean,
|
|
86
|
+
enough?: (events: NostrEvent[]) => boolean): Promise<NostrEvent[]> => {
|
|
87
|
+
if (!urls.length) throw new VaultRelayError('No valid vault relays', [])
|
|
88
|
+
const events = new Map<string, NostrEvent>()
|
|
89
|
+
const failed: string[] = []
|
|
90
|
+
await Promise.all(urls.map(async url => {
|
|
91
|
+
let relay: RelayClient | undefined
|
|
92
|
+
try {
|
|
93
|
+
relay = new RelayClient(url)
|
|
94
|
+
await relay.connect()
|
|
95
|
+
const found = await fetchVaultEvents(relay, filter, undefined, accept)
|
|
96
|
+
for (const e of found) events.set(e.id, e)
|
|
97
|
+
} catch { failed.push(url) }
|
|
98
|
+
finally { relay?.disconnect() }
|
|
99
|
+
}))
|
|
100
|
+
const result = [...events.values()]
|
|
101
|
+
if (failed.length && !(enough && enough(result))) {
|
|
102
|
+
throw new VaultRelayError(`Vault relays did not all answer: ${failed.length} of ${urls.length} failed`, failed.sort())
|
|
103
|
+
}
|
|
104
|
+
return result
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
checkpoints: (author, dTag) => query({ kinds: [VAULT_EVENT_KIND], authors: [author], ...(dTag ? { '#d': [dTag] } : {}), limit: MAX_VAULT_EVENTS_PER_RELAY },
|
|
108
|
+
event => vaultCheckpointShapedTag(event) !== null),
|
|
109
|
+
chunk: async id => (await query({ ids: [id], limit: 1 }, undefined, found => found.some(e => e.id === id))).find(e => e.id === id) ?? null,
|
|
110
|
+
open,
|
|
111
|
+
}
|
|
112
|
+
}
|