libp2r2p 0.12.12 → 0.12.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -13
- package/package.json +1 -1
- package/private-message/helpers/timestamp.js +69 -0
- package/private-message/index.js +31 -4
- package/private-messenger/index.js +123 -19
package/README.md
CHANGED
|
@@ -362,21 +362,29 @@ await messenger.tell({
|
|
|
362
362
|
### Inbound message coalescing
|
|
363
363
|
|
|
364
364
|
`PrivateMessenger` accepts an optional synchronous
|
|
365
|
-
`resolveInboundCoalescing(message, { idempotencyKey })`
|
|
366
|
-
The enriched `message` includes `type` and
|
|
367
|
-
`null` or `{ key, keep?, sequence? }`,
|
|
368
|
-
SHA-256 digest, `keep` is `latest`
|
|
369
|
-
optional non-negative safe integer.
|
|
370
|
-
compared only within records sharing
|
|
365
|
+
`resolveInboundCoalescing(message, { idempotencyKey, eventCreatedAtMs })`
|
|
366
|
+
constructor callback. The enriched `message` includes `type` and
|
|
367
|
+
`channelPubkey`. The callback returns `null` or `{ key, keep?, sequence? }`,
|
|
368
|
+
where `key` is a lowercase 64-character SHA-256 digest, `keep` is `latest`
|
|
369
|
+
(default) or `oldest`, and `sequence` is an optional non-negative safe integer.
|
|
370
|
+
Sequence units are resolver-owned and are compared only within records sharing
|
|
371
|
+
the final scoped coalescing key.
|
|
371
372
|
|
|
372
373
|
The resolver runs for ask, reply, tell, yell, message and nym deliveries after
|
|
373
374
|
exact event-ID deduplication. The final coalescing key is scoped by channel,
|
|
374
375
|
sender, type, message code and provenance. `latest` replaces the pending item in
|
|
375
|
-
place
|
|
376
|
-
`created_at
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
376
|
+
place. Its order is: explicit sequence; `eventCreatedAtMs`, read from the inner
|
|
377
|
+
`created_at` plus the `ms` tag; outer `created_at`; event ID. `oldest` preserves
|
|
378
|
+
the pending item. While an item is reserved, both policies allow at most one
|
|
379
|
+
successor. Timestamp and sequence ordering persist in internal queue metadata.
|
|
380
|
+
Older recovered events do not replace newer requests.
|
|
381
|
+
|
|
382
|
+
New high-level ask, reply, tell and yell rumors include exactly one
|
|
383
|
+
`["ms", "0".."999"]` tag and use the same instant to derive inner `created_at`.
|
|
384
|
+
Missing `ms` means zero for legacy messages; malformed or duplicate tags also
|
|
385
|
+
order as zero and are reported only through sanitized debug diagnostics.
|
|
386
|
+
`message`, `nym`, broadcast rumors and signed-event APIs do not interpret `ms`
|
|
387
|
+
automatically.
|
|
380
388
|
|
|
381
389
|
For ask, reply, tell and yell, exactly one `["D", key]` tag may serve as an
|
|
382
390
|
automatic fallback when the resolver returns `null`. Its key is non-empty and
|
|
@@ -392,6 +400,22 @@ Coalescing does not provide an ingress rate limit or per-peer quota. Exact
|
|
|
392
400
|
event deduplication, authorization, quarantine, global inbox capacity,
|
|
393
401
|
pause/ACK/NACK ownership and existing storage policy remain independent.
|
|
394
402
|
|
|
403
|
+
### Inbound peer admission
|
|
404
|
+
|
|
405
|
+
`PrivateMessenger` accepts an optional synchronous
|
|
406
|
+
`admitInboundPeer(message, context)` callback. It runs after decryption and
|
|
407
|
+
lifecycle gates, but before typed handlers, automatic replies, seed ingestion
|
|
408
|
+
and inbox admission. The context contains `type`, `channelPubkey`,
|
|
409
|
+
`senderPubkey`, `code`, `bytes` and `now`.
|
|
410
|
+
|
|
411
|
+
Returning `false` drops that delivery locally without an operational error or
|
|
412
|
+
NACK. A thrown error, Promise or non-boolean result fails open: the message is
|
|
413
|
+
admitted and the error is reported. The hook is disabled by default and does
|
|
414
|
+
not coalesce, authorize or persist limits itself.
|
|
415
|
+
|
|
416
|
+
Direct ask/reply/tell/yell events invoke their typed callback once and do not
|
|
417
|
+
invoke `onMessage` again for admission purposes.
|
|
418
|
+
|
|
395
419
|
### Deleting Private Broadcasts
|
|
396
420
|
|
|
397
421
|
By default, each high-level private-message send creates one fresh deletion
|
|
@@ -1377,8 +1401,10 @@ signatures, and routed only for the pending peers. The legacy
|
|
|
1377
1401
|
`preparedPublication` public argument is rejected with
|
|
1378
1402
|
`LEGACY_PREPARED_PUBLICATION`; existing encrypted outbox snapshots containing
|
|
1379
1403
|
`prepared.publication` are migrated internally to
|
|
1380
|
-
`prepared.publications` before processing. `yell`
|
|
1381
|
-
|
|
1404
|
+
`prepared.publications` before processing. New `yell` replays pass the original
|
|
1405
|
+
`createdAtMs` so the inner rumor identity matches. Legacy prepared inners
|
|
1406
|
+
without `ms` are detected and replayed without adding the tag; a prepared inner
|
|
1407
|
+
that requires an unavailable `createdAtMs` fails with `CREATED_AT_MS_REQUIRED`.
|
|
1382
1408
|
`broadcastRumor` and `broadcastEvent` already carry their original inner event.
|
|
1383
1409
|
Nym broadcasts intentionally remain a single carrier union.
|
|
1384
1410
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { ValidationError } from '../../error/index.js'
|
|
2
|
+
|
|
3
|
+
export const MILLISECONDS_TAG = 'ms'
|
|
4
|
+
|
|
5
|
+
const CANONICAL_MILLISECONDS = /^(0|[1-9][0-9]{0,2})$/
|
|
6
|
+
|
|
7
|
+
function normalizeCreatedAt (createdAt) {
|
|
8
|
+
if (!Number.isSafeInteger(createdAt) || createdAt < 0) throw new ValidationError('INVALID_CREATED_AT')
|
|
9
|
+
return createdAt
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function timestampFromMilliseconds (createdAtMs) {
|
|
13
|
+
if (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) {
|
|
14
|
+
throw new ValidationError('INVALID_CREATED_AT_MS')
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
createdAt: Math.floor(createdAtMs / 1000),
|
|
18
|
+
milliseconds: createdAtMs % 1000
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function messageTimestamp ({ createdAt, createdAtMs, nowMs = Date.now } = {}) {
|
|
23
|
+
if (createdAtMs != null) {
|
|
24
|
+
const timestamp = timestampFromMilliseconds(createdAtMs)
|
|
25
|
+
if (createdAt != null && normalizeCreatedAt(createdAt) !== timestamp.createdAt) {
|
|
26
|
+
throw new ValidationError('INVALID_CREATED_AT_MS')
|
|
27
|
+
}
|
|
28
|
+
return timestamp
|
|
29
|
+
}
|
|
30
|
+
if (createdAt != null) return { createdAt: normalizeCreatedAt(createdAt), milliseconds: 0 }
|
|
31
|
+
const current = nowMs()
|
|
32
|
+
if (!Number.isSafeInteger(current) || current < 0) throw new ValidationError('INVALID_CREATED_AT_MS')
|
|
33
|
+
return {
|
|
34
|
+
createdAt: Math.floor(current / 1000),
|
|
35
|
+
milliseconds: current % 1000
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function setMillisecondsTag (tags, milliseconds) {
|
|
40
|
+
if (!Number.isSafeInteger(milliseconds) || milliseconds < 0 || milliseconds > 999) {
|
|
41
|
+
throw new ValidationError('INVALID_MILLISECONDS')
|
|
42
|
+
}
|
|
43
|
+
const out = (Array.isArray(tags) ? tags : [])
|
|
44
|
+
.filter(tag => !Array.isArray(tag) || tag[0] !== MILLISECONDS_TAG)
|
|
45
|
+
.map(tag => Array.isArray(tag) ? [...tag] : tag)
|
|
46
|
+
out.push([MILLISECONDS_TAG, String(milliseconds)])
|
|
47
|
+
return out
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function readMilliseconds (event) {
|
|
51
|
+
const tags = (event?.tags || []).filter(tag => Array.isArray(tag) && tag[0] === MILLISECONDS_TAG)
|
|
52
|
+
if (!tags.length) return { milliseconds: 0, reason: 'missing' }
|
|
53
|
+
if (tags.length !== 1 || tags[0].length !== 2 || !CANONICAL_MILLISECONDS.test(tags[0][1])) {
|
|
54
|
+
return { milliseconds: 0, reason: tags.length === 1 ? 'invalid' : 'duplicate' }
|
|
55
|
+
}
|
|
56
|
+
const milliseconds = Number(tags[0][1])
|
|
57
|
+
if (!Number.isInteger(milliseconds) || milliseconds < 0 || milliseconds > 999) {
|
|
58
|
+
return { milliseconds: 0, reason: 'invalid' }
|
|
59
|
+
}
|
|
60
|
+
return { milliseconds, reason: '' }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function eventCreatedAtMs (event, { readMillisecondsTag = true } = {}) {
|
|
64
|
+
if (!Number.isSafeInteger(event?.created_at) || event.created_at < 0) return 0
|
|
65
|
+
const { milliseconds } = readMillisecondsTag
|
|
66
|
+
? readMilliseconds(event)
|
|
67
|
+
: { milliseconds: 0 }
|
|
68
|
+
return event.created_at * 1000 + milliseconds
|
|
69
|
+
}
|
package/private-message/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import * as privateChannel from '../private-channel/index.js'
|
|
|
6
6
|
import { normalizeRumor, deliveryInfo } from '../private-channel/helpers/rumor.js'
|
|
7
7
|
import { normalizePreparedPublications } from '../private-channel/helpers/prepared.js'
|
|
8
8
|
import { appendIdempotencyTag } from './helpers/idempotency.js'
|
|
9
|
+
import { messageTimestamp, setMillisecondsTag } from './helpers/timestamp.js'
|
|
9
10
|
|
|
10
11
|
export const ASK_KIND = 7329
|
|
11
12
|
export const REPLY_KIND = 7330
|
|
@@ -153,18 +154,38 @@ function cloneTags (tags) {
|
|
|
153
154
|
return tags.map(tag => Array.isArray(tag) ? [...tag] : tag)
|
|
154
155
|
}
|
|
155
156
|
|
|
156
|
-
async function makeOutgoingRumor ({ senderSigner, rumor }) {
|
|
157
|
+
async function makeOutgoingRumor ({ senderSigner, rumor, timestamped = false, createdAtMs }) {
|
|
157
158
|
if (!senderSigner?.getPublicKey) throw new ValidationError('SENDER_SIGNER_REQUIRED')
|
|
158
159
|
const senderPubkey = await senderSigner.getPublicKey()
|
|
159
160
|
if (rumor.pubkey !== undefined && rumor.pubkey !== senderPubkey && rumor.created_at === undefined) {
|
|
160
161
|
throw new ValidationError('FORWARDED_RUMOR_TIMESTAMP_REQUIRED')
|
|
161
162
|
}
|
|
162
|
-
const
|
|
163
|
+
const timestamp = messageTimestamp({ createdAt: rumor.created_at, createdAtMs })
|
|
164
|
+
const tags = timestamped
|
|
165
|
+
? setMillisecondsTag(rumor.tags, timestamp.milliseconds)
|
|
166
|
+
: cloneTags(rumor.tags)
|
|
167
|
+
const event = normalizeRumor({ ...rumor, tags, created_at: timestamp.createdAt }, senderPubkey)
|
|
163
168
|
const { id: _, pubkey, ...template } = event
|
|
164
169
|
const wireEvent = pubkey === senderPubkey ? template : { ...template, pubkey }
|
|
165
170
|
return { event, wireEvent }
|
|
166
171
|
}
|
|
167
172
|
|
|
173
|
+
function preparedInnerEventsMatch (publications, event) {
|
|
174
|
+
return publications.length > 0 && publications.every(publication => (
|
|
175
|
+
publication?.innerEventId && publication.innerEventId === event?.id
|
|
176
|
+
))
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function makeYellRumor ({ senderSigner, rumor, createdAtMs, prepared }) {
|
|
180
|
+
const timestamped = await makeOutgoingRumor({ senderSigner, rumor, timestamped: true, createdAtMs })
|
|
181
|
+
if (!prepared.length || preparedInnerEventsMatch(prepared, timestamped.event)) return timestamped
|
|
182
|
+
|
|
183
|
+
const legacy = await makeOutgoingRumor({ senderSigner, rumor })
|
|
184
|
+
if (preparedInnerEventsMatch(prepared, legacy.event)) return legacy
|
|
185
|
+
if (createdAtMs == null) throw new ValidationError('CREATED_AT_MS_REQUIRED')
|
|
186
|
+
throw new ValidationError('INVALID_PREPARED_PUBLICATION')
|
|
187
|
+
}
|
|
188
|
+
|
|
168
189
|
function assertValidSignedEvent (event) {
|
|
169
190
|
if (!isValidEvent(event)) {
|
|
170
191
|
throw new ValidationError('INVALID_SIGNED_EVENT')
|
|
@@ -744,6 +765,7 @@ export async function ask ({
|
|
|
744
765
|
|
|
745
766
|
const { event: question, wireEvent } = await makeOutgoingRumor({
|
|
746
767
|
senderSigner,
|
|
768
|
+
timestamped: true,
|
|
747
769
|
rumor: makeMessageRumor({
|
|
748
770
|
kind: ASK_KIND,
|
|
749
771
|
tags: [['r', receiverPubkey]],
|
|
@@ -788,6 +810,7 @@ export async function reply ({
|
|
|
788
810
|
if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
|
|
789
811
|
const { event, wireEvent } = await makeOutgoingRumor({
|
|
790
812
|
senderSigner,
|
|
813
|
+
timestamped: true,
|
|
791
814
|
rumor: makeMessageRumor({
|
|
792
815
|
kind: REPLY_KIND,
|
|
793
816
|
tags: [['q', question.id], ['r', receiverPubkey]],
|
|
@@ -829,6 +852,7 @@ export async function tell ({
|
|
|
829
852
|
if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
|
|
830
853
|
const { event, wireEvent } = await makeOutgoingRumor({
|
|
831
854
|
senderSigner,
|
|
855
|
+
timestamped: true,
|
|
832
856
|
rumor: makeMessageRumor({
|
|
833
857
|
kind: TELL_KIND,
|
|
834
858
|
tags: [['r', receiverPubkey]],
|
|
@@ -865,6 +889,7 @@ export async function yell ({
|
|
|
865
889
|
autoDeletionCapability = true,
|
|
866
890
|
fileChunkIndex,
|
|
867
891
|
createdAt,
|
|
892
|
+
createdAtMs,
|
|
868
893
|
onPreparedSeed,
|
|
869
894
|
preparedPublication,
|
|
870
895
|
preparedPublications,
|
|
@@ -882,9 +907,11 @@ export async function yell ({
|
|
|
882
907
|
idempotencyKey
|
|
883
908
|
})
|
|
884
909
|
if (createdAt !== undefined) rumor.created_at = createdAt
|
|
885
|
-
const { event, wireEvent } = await
|
|
910
|
+
const { event, wireEvent } = await makeYellRumor({
|
|
886
911
|
senderSigner,
|
|
887
|
-
rumor
|
|
912
|
+
rumor,
|
|
913
|
+
createdAtMs,
|
|
914
|
+
prepared
|
|
888
915
|
})
|
|
889
916
|
const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability, preparedPublications: prepared })
|
|
890
917
|
const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
|
|
@@ -72,6 +72,7 @@ import { DEFAULT_RECEIVED_CHUNK_TTL_MS } from '../private-channel/services/recei
|
|
|
72
72
|
import { createQueue } from '../idb-queue/index.js'
|
|
73
73
|
import { createChannelStateStore } from './services/channel-state.js'
|
|
74
74
|
import { normalizeIdempotencyKey, readIdempotencyKey } from '../private-message/helpers/idempotency.js'
|
|
75
|
+
import { eventCreatedAtMs, readMilliseconds } from '../private-message/helpers/timestamp.js'
|
|
75
76
|
import { DEFAULT_STALE_CHANNEL_SECONDS } from './constants/index.js'
|
|
76
77
|
import {
|
|
77
78
|
activatePrivateMessengerStorage,
|
|
@@ -130,6 +131,11 @@ const COALESCING_INDEX = 'byCoalescingKey'
|
|
|
130
131
|
const COALESCING_DIGEST = /^[0-9a-f]{64}$/
|
|
131
132
|
const COALESCING_KEEP = new Set(['oldest', 'latest'])
|
|
132
133
|
const DEDUPE_TYPES = new Set(['ask', 'reply', 'tell', 'yell'])
|
|
134
|
+
const TIMESTAMPED_PRIVATE_MESSAGE_KINDS = new Set([
|
|
135
|
+
privateMessage.ASK_KIND,
|
|
136
|
+
privateMessage.REPLY_KIND,
|
|
137
|
+
privateMessage.TELL_KIND
|
|
138
|
+
])
|
|
133
139
|
const MESSAGE_QUEUE_INDEXES = {
|
|
134
140
|
byChannel: 'channelPubkey',
|
|
135
141
|
[COALESCING_INDEX]: 'coalescingKey',
|
|
@@ -312,6 +318,7 @@ export class PrivateMessenger {
|
|
|
312
318
|
onDebug,
|
|
313
319
|
onError = defaultOnError,
|
|
314
320
|
resolveInboundCoalescing,
|
|
321
|
+
admitInboundPeer,
|
|
315
322
|
_privateMessage = privateMessage,
|
|
316
323
|
_privateChannel = privateChannel,
|
|
317
324
|
_getRelaysByPubkey = getRelaysByPubkey,
|
|
@@ -336,6 +343,9 @@ export class PrivateMessenger {
|
|
|
336
343
|
if (resolveInboundCoalescing != null && typeof resolveInboundCoalescing !== 'function') {
|
|
337
344
|
throw new ValidationError('INVALID_RESOLVE_INBOUND_COALESCING')
|
|
338
345
|
}
|
|
346
|
+
if (admitInboundPeer != null && typeof admitInboundPeer !== 'function') {
|
|
347
|
+
throw new ValidationError('INVALID_ADMIT_INBOUND_PEER')
|
|
348
|
+
}
|
|
339
349
|
this.fallbackRelays = normalizeFallbackRelays(fallbackRelays)
|
|
340
350
|
this.fallbackDelayMs = normalizeFallbackDelay(fallbackDelayMs)
|
|
341
351
|
this.offlineRecoverySeconds = normalizeOfflineRecoverySeconds(offlineRecoverySeconds)
|
|
@@ -381,6 +391,7 @@ export class PrivateMessenger {
|
|
|
381
391
|
this.onMessageQueued = onMessageQueued
|
|
382
392
|
this.onDebug = onDebug
|
|
383
393
|
this.resolveInboundCoalescing = resolveInboundCoalescing
|
|
394
|
+
this.admitInboundPeer = admitInboundPeer
|
|
384
395
|
this._privateMessage = _privateMessage.createPrivateMessageSession?.() ?? _privateMessage
|
|
385
396
|
this._privateChannel = _privateChannel
|
|
386
397
|
this._getRelaysByPubkey = _getRelaysByPubkey
|
|
@@ -1326,13 +1337,18 @@ export class PrivateMessenger {
|
|
|
1326
1337
|
privateChannelReaderSigner: channel.readerSigner,
|
|
1327
1338
|
privateChannelReaderPubkey: channel.readerPubkey,
|
|
1328
1339
|
mode: channel.mode,
|
|
1329
|
-
onAsk: message => this.receive(pubkey, () => this.handleAsk(pubkey, message), message),
|
|
1330
|
-
onReply: message => this.receive(pubkey, () => this.handleReply(pubkey, message), message),
|
|
1331
|
-
onTell: message => this.receive(pubkey, () => this.handleTell(pubkey, message), message),
|
|
1332
|
-
onYell: message => this.receive(pubkey, () => this.handleYell(pubkey, message), message),
|
|
1333
|
-
onNym: message => this.receive(pubkey, () => this.handleNym(pubkey, message), message),
|
|
1334
|
-
onMessage: message =>
|
|
1335
|
-
|
|
1340
|
+
onAsk: message => this.receive(pubkey, () => this.handleAsk(pubkey, message), message, { inboundType: 'ask' }),
|
|
1341
|
+
onReply: message => this.receive(pubkey, () => this.handleReply(pubkey, message), message, { inboundType: 'reply' }),
|
|
1342
|
+
onTell: message => this.receive(pubkey, () => this.handleTell(pubkey, message), message, { inboundType: 'tell' }),
|
|
1343
|
+
onYell: message => this.receive(pubkey, () => this.handleYell(pubkey, message), message, { inboundType: 'yell' }),
|
|
1344
|
+
onNym: message => this.receive(pubkey, () => this.handleNym(pubkey, message), message, { inboundType: 'nym' }),
|
|
1345
|
+
onMessage: message => {
|
|
1346
|
+
const type = eventType(message.event)
|
|
1347
|
+
if (type !== 'message' && message.provenance !== 'hearsay' &&
|
|
1348
|
+
(!message.senderPubkey || message.senderPubkey === message.event.pubkey)) return Promise.resolve()
|
|
1349
|
+
return this.receive(pubkey, () => this.handleMessage(pubkey, message), message, { inboundType: 'message' })
|
|
1350
|
+
},
|
|
1351
|
+
onSeed: seed => this.receive(pubkey, () => this.enqueueSeed(pubkey, seed), seed, { inboundType: 'seed' }),
|
|
1336
1352
|
onContentKeyUsage: usage => this.handleContentKeyUsage(pubkey, usage),
|
|
1337
1353
|
onDecryptionFailure: failure => this.deferDecryption(failure),
|
|
1338
1354
|
_onProcessing: pubkey => this.decryptionScheduler.activity(pubkey),
|
|
@@ -2096,7 +2112,44 @@ export class PrivateMessenger {
|
|
|
2096
2112
|
return jobs
|
|
2097
2113
|
}
|
|
2098
2114
|
|
|
2099
|
-
|
|
2115
|
+
#admitInboundPeer (pubkey, inboundType, message) {
|
|
2116
|
+
if (!this.admitInboundPeer) return true
|
|
2117
|
+
const type = inboundType || 'message'
|
|
2118
|
+
const context = {
|
|
2119
|
+
type,
|
|
2120
|
+
channelPubkey: pubkey,
|
|
2121
|
+
senderPubkey: inboundSenderPubkey(message),
|
|
2122
|
+
code: messageCode(message) || message?.recordType || '',
|
|
2123
|
+
bytes: inboundMessageBytes(message),
|
|
2124
|
+
now: this._now()
|
|
2125
|
+
}
|
|
2126
|
+
let admitted
|
|
2127
|
+
try {
|
|
2128
|
+
admitted = this.admitInboundPeer(
|
|
2129
|
+
{ ...message, type, channelPubkey: pubkey },
|
|
2130
|
+
context
|
|
2131
|
+
)
|
|
2132
|
+
if (admitted != null && typeof admitted.then === 'function') {
|
|
2133
|
+
throw new Error('INBOUND_PEER_ADMISSION_MUST_BE_SYNCHRONOUS')
|
|
2134
|
+
}
|
|
2135
|
+
} catch (cause) {
|
|
2136
|
+
this.onError?.(inboundPeerAdmissionError(cause))
|
|
2137
|
+
return true
|
|
2138
|
+
}
|
|
2139
|
+
if (admitted === false) {
|
|
2140
|
+
this.debug('inbound-peer-dropped', {
|
|
2141
|
+
type,
|
|
2142
|
+
code: context.code
|
|
2143
|
+
})
|
|
2144
|
+
return false
|
|
2145
|
+
}
|
|
2146
|
+
if (admitted !== true) {
|
|
2147
|
+
this.onError?.(inboundPeerAdmissionError(new ValidationError('INVALID_INBOUND_PEER_ADMISSION')))
|
|
2148
|
+
}
|
|
2149
|
+
return true
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
receive (pubkey, operation, message = {}, { trackActivity = true, inboundType = 'message' } = {}) {
|
|
2100
2153
|
if (this.closePromise) {
|
|
2101
2154
|
if (this.storageActive) this.recordInterruption([pubkey], messageTime(message))
|
|
2102
2155
|
return Promise.reject(new Error('PRIVATE_MESSENGER_CLOSED'))
|
|
@@ -2107,6 +2160,7 @@ export class PrivateMessenger {
|
|
|
2107
2160
|
this.recordInterruption([pubkey], messageTime(message))
|
|
2108
2161
|
throw this.pausedError()
|
|
2109
2162
|
}
|
|
2163
|
+
if (!this.#admitInboundPeer(pubkey, inboundType, message)) return
|
|
2110
2164
|
return operation()
|
|
2111
2165
|
}).finally(releaseActivity)
|
|
2112
2166
|
}
|
|
@@ -2218,13 +2272,30 @@ export class PrivateMessenger {
|
|
|
2218
2272
|
reason: tagged.reason
|
|
2219
2273
|
})
|
|
2220
2274
|
}
|
|
2275
|
+
const timestamped = TIMESTAMPED_PRIVATE_MESSAGE_KINDS.has(message.event?.kind)
|
|
2276
|
+
const milliseconds = timestamped
|
|
2277
|
+
? readMilliseconds(message.event)
|
|
2278
|
+
: { milliseconds: 0, reason: '' }
|
|
2279
|
+
if (milliseconds.reason && milliseconds.reason !== 'missing') {
|
|
2280
|
+
this.debug('milliseconds-tag-ignored', {
|
|
2281
|
+
type,
|
|
2282
|
+
code: messageCode(message) || '',
|
|
2283
|
+
reason: milliseconds.reason
|
|
2284
|
+
})
|
|
2285
|
+
}
|
|
2286
|
+
const messageCreatedAtMs = eventCreatedAtMs(message.event, {
|
|
2287
|
+
readMillisecondsTag: timestamped
|
|
2288
|
+
})
|
|
2221
2289
|
|
|
2222
2290
|
let resolved = null
|
|
2223
2291
|
if (this.resolveInboundCoalescing) {
|
|
2224
2292
|
try {
|
|
2225
2293
|
resolved = this.resolveInboundCoalescing(
|
|
2226
2294
|
{ ...message, type, channelPubkey },
|
|
2227
|
-
{
|
|
2295
|
+
{
|
|
2296
|
+
idempotencyKey: tagged.key,
|
|
2297
|
+
eventCreatedAtMs: messageCreatedAtMs
|
|
2298
|
+
}
|
|
2228
2299
|
)
|
|
2229
2300
|
if (resolved != null && typeof resolved?.then === 'function') {
|
|
2230
2301
|
throw new Error('COALESCING_RESOLVER_MUST_BE_SYNCHRONOUS')
|
|
@@ -2270,7 +2341,7 @@ export class PrivateMessenger {
|
|
|
2270
2341
|
digest
|
|
2271
2342
|
]),
|
|
2272
2343
|
coalescingKeep: keep,
|
|
2273
|
-
coalescingOrder: coalescingOrder(message, sequence)
|
|
2344
|
+
coalescingOrder: coalescingOrder(message, sequence, messageCreatedAtMs)
|
|
2274
2345
|
}
|
|
2275
2346
|
}
|
|
2276
2347
|
|
|
@@ -2749,7 +2820,7 @@ export class PrivateMessenger {
|
|
|
2749
2820
|
} finally { releaseActivity() }
|
|
2750
2821
|
}
|
|
2751
2822
|
|
|
2752
|
-
async yell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, createdAt, onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false }) {
|
|
2823
|
+
async yell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, createdAt, createdAtMs, onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false }) {
|
|
2753
2824
|
idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2754
2825
|
const channel = this.requireWritableChannel(channelPubkey)
|
|
2755
2826
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
@@ -2778,6 +2849,7 @@ export class PrivateMessenger {
|
|
|
2778
2849
|
content,
|
|
2779
2850
|
idempotencyKey,
|
|
2780
2851
|
createdAt,
|
|
2852
|
+
createdAtMs,
|
|
2781
2853
|
useBulkPacing,
|
|
2782
2854
|
onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
|
|
2783
2855
|
preparedPublications: prepared.length ? prepared : undefined,
|
|
@@ -3349,9 +3421,9 @@ export class PrivateMessenger {
|
|
|
3349
3421
|
modeByPubkey: { [channelPubkey]: channel.mode },
|
|
3350
3422
|
receivedChunkTtlMs: this.receivedChunkTtlMsFor(channel),
|
|
3351
3423
|
receivedChunkIndexedDB: this._indexedDB,
|
|
3352
|
-
onEvent: (event, outer, meta) => this.receive(channelPubkey, () => this.enqueueRumor(eventType(event), channelPubkey, { event, outer, meta, payload: parseEventContent(event) }), { event, outer }),
|
|
3353
|
-
onNymEvent: (event, outer, meta) => this.receive(channelPubkey, () => this.enqueueRumor('nym', channelPubkey, { event, outer, meta, payload: parseEventContent(event) }), { event, outer }),
|
|
3354
|
-
onSeedEvent: seed => this.receive(channelPubkey, () => this.enqueueSeed(channelPubkey, seed), seed),
|
|
3424
|
+
onEvent: (event, outer, meta) => this.receive(channelPubkey, () => this.enqueueRumor(eventType(event), channelPubkey, { event, outer, meta, payload: parseEventContent(event) }), { event, outer }, { inboundType: eventType(event) }),
|
|
3425
|
+
onNymEvent: (event, outer, meta) => this.receive(channelPubkey, () => this.enqueueRumor('nym', channelPubkey, { event, outer, meta, payload: parseEventContent(event) }), { event, outer }, { inboundType: 'nym' }),
|
|
3426
|
+
onSeedEvent: seed => this.receive(channelPubkey, () => this.enqueueSeed(channelPubkey, seed), seed, { inboundType: 'seed' }),
|
|
3355
3427
|
onContentKeyUsage: usage => this.handleContentKeyUsage(channelPubkey, usage),
|
|
3356
3428
|
onDecryptionFailure: failure => this.deferDecryption(failure),
|
|
3357
3429
|
_onProcessing: pubkey => this.decryptionScheduler.activity(pubkey),
|
|
@@ -3707,13 +3779,13 @@ export class PrivateMessenger {
|
|
|
3707
3779
|
},
|
|
3708
3780
|
onEvent: (event, outer, meta) => {
|
|
3709
3781
|
current()
|
|
3710
|
-
return this.receive(channelPubkey, () => this.enqueueRumor(eventType(event), channelPubkey, { event, outer, meta, payload: parseEventContent(event) }), { event, outer }, { trackActivity: false })
|
|
3782
|
+
return this.receive(channelPubkey, () => this.enqueueRumor(eventType(event), channelPubkey, { event, outer, meta, payload: parseEventContent(event) }), { event, outer }, { trackActivity: false, inboundType: eventType(event) })
|
|
3711
3783
|
},
|
|
3712
3784
|
onNymEvent: (event, outer, meta) => {
|
|
3713
3785
|
current()
|
|
3714
|
-
return this.receive(channelPubkey, () => this.enqueueRumor('nym', channelPubkey, { event, outer, meta, payload: parseEventContent(event) }), { event, outer }, { trackActivity: false })
|
|
3786
|
+
return this.receive(channelPubkey, () => this.enqueueRumor('nym', channelPubkey, { event, outer, meta, payload: parseEventContent(event) }), { event, outer }, { trackActivity: false, inboundType: 'nym' })
|
|
3715
3787
|
},
|
|
3716
|
-
onSeedEvent: seed => { current(); return this.receive(channelPubkey, () => this.enqueueSeed(channelPubkey, seed), seed, { trackActivity: false }) },
|
|
3788
|
+
onSeedEvent: seed => { current(); return this.receive(channelPubkey, () => this.enqueueSeed(channelPubkey, seed), seed, { trackActivity: false, inboundType: 'seed' }) },
|
|
3717
3789
|
onRecovered: async record => {
|
|
3718
3790
|
current()
|
|
3719
3791
|
await callbacks.onRecovered?.(record)
|
|
@@ -3941,8 +4013,9 @@ function messageCode (message) {
|
|
|
3941
4013
|
: null
|
|
3942
4014
|
}
|
|
3943
4015
|
|
|
3944
|
-
function coalescingOrder (message, sequence = null) {
|
|
4016
|
+
function coalescingOrder (message, sequence = null, messageCreatedAtMs = 0) {
|
|
3945
4017
|
const order = {
|
|
4018
|
+
eventTimeMs: messageCreatedAtMs,
|
|
3946
4019
|
outer: Number.isSafeInteger(message?.outer?.created_at) ? message.outer.created_at : 0,
|
|
3947
4020
|
inner: Number.isSafeInteger(message?.event?.created_at) ? message.event.created_at : 0,
|
|
3948
4021
|
eventId: message?.event?.id || ''
|
|
@@ -3956,8 +4029,14 @@ function compareCoalescingOrder (left, right) {
|
|
|
3956
4029
|
left.sequence !== right.sequence) {
|
|
3957
4030
|
return left.sequence < right.sequence ? -1 : 1
|
|
3958
4031
|
}
|
|
4032
|
+
const leftTime = Number.isSafeInteger(left?.eventTimeMs)
|
|
4033
|
+
? left.eventTimeMs
|
|
4034
|
+
: (Number.isSafeInteger(left?.inner) ? left.inner * 1000 : 0)
|
|
4035
|
+
const rightTime = Number.isSafeInteger(right?.eventTimeMs)
|
|
4036
|
+
? right.eventTimeMs
|
|
4037
|
+
: (Number.isSafeInteger(right?.inner) ? right.inner * 1000 : 0)
|
|
4038
|
+
if (leftTime !== rightTime) return leftTime < rightTime ? -1 : 1
|
|
3959
4039
|
if ((left?.outer || 0) !== (right?.outer || 0)) return (left?.outer || 0) - (right?.outer || 0)
|
|
3960
|
-
if ((left?.inner || 0) !== (right?.inner || 0)) return (left?.inner || 0) - (right?.inner || 0)
|
|
3961
4040
|
const leftId = left?.eventId || ''
|
|
3962
4041
|
const rightId = right?.eventId || ''
|
|
3963
4042
|
if (leftId === rightId) return 0
|
|
@@ -4027,6 +4106,31 @@ function messageTime (message) {
|
|
|
4027
4106
|
return message.outer?.created_at || message.event?.created_at || nowSeconds()
|
|
4028
4107
|
}
|
|
4029
4108
|
|
|
4109
|
+
function inboundSenderPubkey (message) {
|
|
4110
|
+
return message?.senderPubkey ||
|
|
4111
|
+
message?.event?.pubkey ||
|
|
4112
|
+
message?.meta?.senderPubkey ||
|
|
4113
|
+
message?.router?.tags?.find(tag => tag[0] === 'f')?.[1] ||
|
|
4114
|
+
''
|
|
4115
|
+
}
|
|
4116
|
+
|
|
4117
|
+
function inboundMessageBytes (message) {
|
|
4118
|
+
const value = message?.event
|
|
4119
|
+
? message.event
|
|
4120
|
+
: message?.recordType ? message : message?.router || message
|
|
4121
|
+
try {
|
|
4122
|
+
return encoder.encode(JSON.stringify(value)).byteLength
|
|
4123
|
+
} catch {
|
|
4124
|
+
return 0
|
|
4125
|
+
}
|
|
4126
|
+
}
|
|
4127
|
+
|
|
4128
|
+
function inboundPeerAdmissionError (cause) {
|
|
4129
|
+
return Object.assign(new Error(cause?.message || 'INVALID_INBOUND_PEER_ADMISSION', { cause }), {
|
|
4130
|
+
code: 'INVALID_INBOUND_PEER_ADMISSION'
|
|
4131
|
+
})
|
|
4132
|
+
}
|
|
4133
|
+
|
|
4030
4134
|
function oldestCreatedAt (events) {
|
|
4031
4135
|
let oldest = null
|
|
4032
4136
|
for (const event of events || []) {
|