libp2r2p 0.12.25 → 0.12.27

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.
@@ -12,9 +12,9 @@ import * as channelTransport from '../../private-channel/index.js'
12
12
  import * as messages from '../../private-message/index.js'
13
13
  import { readFileChunkIndex } from '../../private-channel/helpers/event.js'
14
14
  import { compactSeedRouterRows, compactRecordsFromSeed, createEventReplyPacker, ROUTER_SEED_RECORD_TYPE } from '../recovery/index.js'
15
+ import { FILE_CHUNKS_REQUEST_CODE, FILE_CHUNKS_REPLY_CODE } from '../constants/index.js'
15
16
 
16
- export const FILE_CHUNKS_REQUEST_CODE = 'fileChunksRequest_p5cc'
17
- export const FILE_CHUNKS_REPLY_CODE = 'fileChunksReply_p5cc'
17
+ export { FILE_CHUNKS_REQUEST_CODE, FILE_CHUNKS_REPLY_CODE }
18
18
  export const IRFS_CHUNK_RECORD_TYPE = 'irfsChunk_v1'
19
19
  export const AUTO_DOWNLOAD_BYTES = 1024 * 1024
20
20
  export const FILE_REQUEST_CHUNKS = 16
@@ -110,11 +110,11 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
110
110
  const parent = messenger.channels.get(file.controlChannelPubkey)
111
111
  return ['seeder', 'watchtower'].includes(parent?.mode) && messenger.offlineRecoverySecondsFor(parent) > 0
112
112
  }
113
- async function authorizeSeeding (descriptor, { receiverPubkeys, sharedAt } = {}) {
113
+ async function authorizeSeeding (descriptor, { receiverPubkeys, sharedAt, capacityEgress } = {}) {
114
114
  if (!Array.isArray(receiverPubkeys) || !receiverPubkeys.length || !receiverPubkeys.every(key => typeof key === 'string' && HEX.test(key))) throw new ValidationError('INVALID_FILE_AUTHORIZATION_RECEIVERS')
115
115
  if (!Number.isSafeInteger(sharedAt) || sharedAt < 0) throw new ValidationError('INVALID_FILE_SHARED_AT')
116
116
  const file = await register(descriptor)
117
- usable(file)
117
+ usable(file, { capacityEgress })
118
118
  await catalog.authorize(file, [...new Set(receiverPubkeys)], sharedAt)
119
119
  }
120
120
  async function prune () {
@@ -152,9 +152,9 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
152
152
  function sendOptions (file, routes) {
153
153
  return { senderSigner: messenger.userSigner, imkcSigner: messenger.contentKeySigner, privateChannelSigner: file.signer, ...routes, temporaryStorageArea: messenger.temporaryStorageArea, expirationSeconds: messenger.eventExpirationSecondsFor(file.controlChannelPubkey), useBulkPacing: true, _getIykcProofs: messenger.contentKeyLookup() }
154
154
  }
155
- async function publishChunk (descriptor, event, { signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug } = {}) {
155
+ async function publishChunk (descriptor, event, { signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, capacityEgress } = {}) {
156
156
  const file = await register(descriptor)
157
- usable(file)
157
+ usable(file, { capacityEgress })
158
158
  const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
159
159
  const decoded = checked(file, event)
160
160
  await catalog.ready
@@ -164,7 +164,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
164
164
  }
165
165
  let result
166
166
  try {
167
- const options = { ...sendOptions(file, await routing(file, file.peerPubkey, signal, attemptStartedAt, onDebug)), receiverPubkeys: [file.peerPubkey], fileChunkIndex: decoded.index, preparedPublications: prepared.length ? prepared : undefined, ...(onPreparedSeed ? { onPreparedSeed } : messenger.channels.get(file.controlChannelPubkey)?.mode === 'watchtower' ? { onPreparedSeed: seed => saveSeed(file, seed) } : {}) }
167
+ const options = { ...sendOptions(file, await routing(file, file.peerPubkey, signal, attemptStartedAt, onDebug, { capacityEgress })), receiverPubkeys: [file.peerPubkey], fileChunkIndex: decoded.index, preparedPublications: prepared.length ? prepared : undefined, ...(onPreparedSeed ? { onPreparedSeed } : messenger.channels.get(file.controlChannelPubkey)?.mode === 'watchtower' ? { onPreparedSeed: seed => saveSeed(file, seed) } : {}) }
168
168
  result = event.sig ? await _messages.broadcastEvent({ ...options, event }) : await _messages.broadcastRumor({ ...options, rumor: event })
169
169
  await assertMessagePublished(result, result?.rumor || result?.event || { ...event, pubkey: event.pubkey || messenger.userPubkey })
170
170
  } catch (error) { await uploadLeases.get(file.root)?.(); uploadLeases.delete(file.root); throw error }
@@ -199,6 +199,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
199
199
  code: FILE_CHUNKS_REPLY_CODE,
200
200
  idempotencyKey: `${FILE_CHUNKS_REPLY_CODE}:${question.id}:${file.root}`,
201
201
  eventsPerChunk: 1,
202
+ seedable: false,
202
203
  recordsFromInput: record => [record]
203
204
  })
204
205
  for (const index of indices) {
@@ -240,6 +241,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
240
241
  code: FILE_CHUNKS_REPLY_CODE,
241
242
  idempotencyKey: `${FILE_CHUNKS_REPLY_CODE}:${question.id}:${file.root}`,
242
243
  eventsPerChunk: 1,
244
+ seedable: false,
243
245
  recordsFromInput: row => compactRecordsFromSeed(row, { receiverPubkey: question.pubkey })
244
246
  })
245
247
  }
@@ -369,7 +371,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
369
371
  requestedSeeders.add(peer)
370
372
  requestRoundAt = Date.now() + _hedgeMs
371
373
  // The request is on dm; its compact reply is on the file channel.
372
- await messenger.ask({ channelPubkey: file.controlChannelPubkey, receiverPubkey: peer, code: FILE_CHUNKS_REQUEST_CODE, payload: { fileChannelPubkey: file.fileChannelPubkey, missingRanges: rangesFor(missing) } }).catch(reportError)
374
+ await messenger.ask({ channelPubkey: file.controlChannelPubkey, receiverPubkey: peer, code: FILE_CHUNKS_REQUEST_CODE, seedable: false, payload: { fileChannelPubkey: file.fileChannelPubkey, missingRanges: rangesFor(missing) } }).catch(reportError)
373
375
  }
374
376
  if (!remaining.length && Date.now() - Math.max(lastProgress, requestRoundAt - _hedgeMs) >= _idleMs) {
375
377
  const details = {
@@ -79,7 +79,7 @@ import { classifyEvent, isEphemeralEvent } from '../event/index.js'
79
79
  import { createChannelStateStore } from './services/channel-state.js'
80
80
  import { normalizeIdempotencyKey, readIdempotencyKey } from '../private-message/helpers/idempotency.js'
81
81
  import { eventCreatedAtMs, readMilliseconds } from '../private-message/helpers/timestamp.js'
82
- import { DEFAULT_STALE_CHANNEL_SECONDS } from './constants/index.js'
82
+ import { DEFAULT_STALE_CHANNEL_SECONDS, FILE_CHUNKS_REPLY_CODE, FILE_CHUNKS_REQUEST_CODE } from './constants/index.js'
83
83
  import {
84
84
  activatePrivateMessengerStorage,
85
85
  DEFAULT_IDENTITY_STORAGE_RETENTION_SECONDS,
@@ -147,6 +147,45 @@ const DELIVERY_PRIORITY = Object.freeze({
147
147
  normal: 2
148
148
  })
149
149
  const DELIVERY_PRIORITY_NAMES = new Set(Object.keys(DELIVERY_PRIORITY))
150
+ const DEFAULT_RESERVE_PRIORITIES = Object.freeze([
151
+ DELIVERY_PRIORITY.normal,
152
+ DELIVERY_PRIORITY.lower,
153
+ DELIVERY_PRIORITY.lowest
154
+ ])
155
+ const NON_SEEDABLE_PROTOCOL_CODES = new Set([
156
+ SEEDER_PRESENCE_CODE,
157
+ MISSING_MESSAGES_ASK_CODE,
158
+ MISSING_MESSAGES_REPLY_CODE,
159
+ FILE_CHUNKS_REQUEST_CODE,
160
+ FILE_CHUNKS_REPLY_CODE
161
+ ])
162
+
163
+ function assertSeedableOption (seedable) {
164
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
165
+ }
166
+
167
+ function resolvedMessageCode (message, code) {
168
+ if (message && typeof message === 'object' && message.code != null) return String(message.code)
169
+ return code == null ? '' : String(code)
170
+ }
171
+
172
+ function normalizeReservePriorities (priorities) {
173
+ if (priorities === undefined) return DEFAULT_RESERVE_PRIORITIES
174
+ if (!Array.isArray(priorities) || !priorities.length) {
175
+ throw new ValidationError('INVALID_DELIVERY_PRIORITIES')
176
+ }
177
+ const seen = new Set()
178
+ const mapped = []
179
+ for (const name of priorities) {
180
+ if (typeof name !== 'string' || !DELIVERY_PRIORITY_NAMES.has(name)) {
181
+ throw new ValidationError('INVALID_DELIVERY_PRIORITIES')
182
+ }
183
+ if (seen.has(name)) continue
184
+ seen.add(name)
185
+ mapped.push(DELIVERY_PRIORITY[name])
186
+ }
187
+ return mapped
188
+ }
150
189
  const PROVENANCE_PRIORITY = {
151
190
  signed: 2,
152
191
  direct: 1,
@@ -378,6 +417,7 @@ export class PrivateMessenger {
378
417
  onError = defaultOnError,
379
418
  resolveInboundCoalescing,
380
419
  resolveInboundPriority,
420
+ resolveInboundSeedable,
381
421
  admitInboundPeer,
382
422
  _privateMessage = privateMessage,
383
423
  _privateChannel = privateChannel,
@@ -406,6 +446,9 @@ export class PrivateMessenger {
406
446
  if (resolveInboundPriority != null && typeof resolveInboundPriority !== 'function') {
407
447
  throw new ValidationError('INVALID_RESOLVE_INBOUND_PRIORITY')
408
448
  }
449
+ if (resolveInboundSeedable != null && typeof resolveInboundSeedable !== 'function') {
450
+ throw new ValidationError('INVALID_RESOLVE_INBOUND_SEEDABLE')
451
+ }
409
452
  if (admitInboundPeer != null && typeof admitInboundPeer !== 'function') {
410
453
  throw new ValidationError('INVALID_ADMIT_INBOUND_PEER')
411
454
  }
@@ -457,6 +500,7 @@ export class PrivateMessenger {
457
500
  this.onDebug = onDebug
458
501
  this.resolveInboundCoalescing = resolveInboundCoalescing
459
502
  this.resolveInboundPriority = resolveInboundPriority
503
+ this.resolveInboundSeedable = resolveInboundSeedable
460
504
  this.admitInboundPeer = admitInboundPeer
461
505
  this._privateMessage = _privateMessage.createPrivateMessageSession?.() ?? _privateMessage
462
506
  this._privateChannel = _privateChannel
@@ -2757,8 +2801,39 @@ export class PrivateMessenger {
2757
2801
  return seed => this.enqueueSeed(channelPubkey, seed)
2758
2802
  }
2759
2803
 
2804
+ shouldSeedInbound (channelPubkey, seed) {
2805
+ if (!seed) return false
2806
+ if (seed.router && !privateChannel.isRouterSeedable(seed.router)) return false
2807
+ if (seed.event) {
2808
+ let payload = null
2809
+ try { payload = privateMessage.parseRumorContent(seed.event) } catch {}
2810
+ const code = isPlainObject(payload) && typeof payload.code === 'string' ? payload.code : ''
2811
+ if (code && NON_SEEDABLE_PROTOCOL_CODES.has(code)) return false
2812
+ if (this.resolveInboundSeedable) {
2813
+ try {
2814
+ const decision = this.resolveInboundSeedable({
2815
+ event: seed.event,
2816
+ outer: seed.outer,
2817
+ router: seed.router,
2818
+ channelPubkey,
2819
+ code,
2820
+ payload
2821
+ })
2822
+ if (decision === false) return false
2823
+ if (decision !== true && decision != null) {
2824
+ this.onError?.(new ValidationError('INVALID_RESOLVE_INBOUND_SEEDABLE_RESULT'))
2825
+ }
2826
+ } catch (error) {
2827
+ this.onError?.(error)
2828
+ }
2829
+ }
2830
+ }
2831
+ return true
2832
+ }
2833
+
2760
2834
  async enqueueSeed (channelPubkey, seed) {
2761
2835
  if (!this.offlineRecoverySecondsFor(channelPubkey)) return
2836
+ if (!this.shouldSeedInbound(channelPubkey, seed)) return
2762
2837
  if (this.seedStorage) {
2763
2838
  const receivedAt = nowSeconds()
2764
2839
  const rows = seed.recordType === NYM_CARRIER_SEED_RECORD_TYPE || seed.carriers?.length
@@ -2962,14 +3037,15 @@ export class PrivateMessenger {
2962
3037
  }
2963
3038
 
2964
3039
  // A cancellable iterator, including while next() is waiting on an empty queue.
2965
- messages () {
3040
+ messages (options = {}) {
3041
+ normalizeReservePriorities(options?.priorities)
2966
3042
  let cancelled = false
2967
3043
  const held = new Set()
2968
3044
  let tail = Promise.resolve()
2969
3045
  const next = async () => {
2970
3046
  while (true) {
2971
3047
  if (cancelled || this.closePromise) break
2972
- const delivery = await this.nextMessage()
3048
+ const delivery = await this.nextMessage({ priorities: options?.priorities })
2973
3049
  if (delivery) {
2974
3050
  if (cancelled || this.closePromise) { await delivery.nack(); break }
2975
3051
  held.add(delivery)
@@ -2998,25 +3074,26 @@ export class PrivateMessenger {
2998
3074
  }
2999
3075
  }
3000
3076
 
3001
- nextMessage () {
3002
- const work = this.reserveMessage()
3077
+ get supportsPriorityLanes () {
3078
+ return true
3079
+ }
3080
+
3081
+ nextMessage (options = {}) {
3082
+ const priorities = normalizeReservePriorities(options?.priorities)
3083
+ const work = this.reserveMessage({ priorities })
3003
3084
  this.deliveryReads.add(work)
3004
3085
  work.then(() => this.deliveryReads.delete(work), () => this.deliveryReads.delete(work))
3005
3086
  return work
3006
3087
  }
3007
3088
 
3008
- async reserveMessage () {
3089
+ async reserveMessage ({ priorities = DEFAULT_RESERVE_PRIORITIES } = {}) {
3009
3090
  this.assertOpen()
3010
3091
  this.touchStorageActivity().catch(err => this.onError?.(err))
3011
3092
  await this.queueOperationTail
3012
3093
  const reservation = await this.queue.reserve({
3013
3094
  nackCoalescingIndex: COALESCING_INDEX,
3014
3095
  priorityIndex: DELIVERY_PRIORITY_INDEX,
3015
- priorities: [
3016
- DELIVERY_PRIORITY.normal,
3017
- DELIVERY_PRIORITY.lower,
3018
- DELIVERY_PRIORITY.lowest
3019
- ]
3096
+ priorities
3020
3097
  })
3021
3098
  if (!reservation) return null
3022
3099
  if (this.closePromise) { await reservation.nack(); return null }
@@ -3067,8 +3144,11 @@ export class PrivateMessenger {
3067
3144
  async ask (options = {}) {
3068
3145
  const {
3069
3146
  channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers,
3070
- message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false
3147
+ message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false,
3148
+ seedable = true
3071
3149
  } = options
3150
+ assertSeedableOption(seedable)
3151
+ const effectiveSeedable = seedable && !NON_SEEDABLE_PROTOCOL_CODES.has(resolvedMessageCode(message, code))
3072
3152
  const capacityEgress = this.capacityEgressFor(options)
3073
3153
  const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
3074
3154
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
@@ -3094,7 +3174,8 @@ export class PrivateMessenger {
3094
3174
  content,
3095
3175
  idempotencyKey: normalizedIdempotencyKey,
3096
3176
  useBulkPacing,
3097
- onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
3177
+ seedable: effectiveSeedable,
3178
+ onPreparedSeed: effectiveSeedable ? this.outgoingSeedHandler(channelPubkey) : undefined,
3098
3179
  _getIykcProofs: this.contentKeyLookup()
3099
3180
  })
3100
3181
  } finally { releaseActivity() }
@@ -3103,8 +3184,11 @@ export class PrivateMessenger {
3103
3184
  async reply (options = {}) {
3104
3185
  const {
3105
3186
  channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers,
3106
- message, code, payload, error, content, idempotencyKey, deletionPubkey, expiresAt, useBulkPacing = false
3187
+ message, code, payload, error, content, idempotencyKey, deletionPubkey, expiresAt, useBulkPacing = false,
3188
+ seedable = true
3107
3189
  } = options
3190
+ assertSeedableOption(seedable)
3191
+ const effectiveSeedable = seedable && !NON_SEEDABLE_PROTOCOL_CODES.has(resolvedMessageCode(message, code))
3108
3192
  const capacityEgress = this.capacityEgressFor(options)
3109
3193
  const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
3110
3194
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
@@ -3137,7 +3221,8 @@ export class PrivateMessenger {
3137
3221
  content,
3138
3222
  idempotencyKey: normalizedIdempotencyKey,
3139
3223
  useBulkPacing,
3140
- onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
3224
+ seedable: effectiveSeedable,
3225
+ onPreparedSeed: effectiveSeedable ? this.outgoingSeedHandler(channelPubkey) : undefined,
3141
3226
  _getIykcProofs: this.contentKeyLookup()
3142
3227
  })
3143
3228
  } finally { releaseActivity() }
@@ -3146,8 +3231,11 @@ export class PrivateMessenger {
3146
3231
  async tell (options = {}) {
3147
3232
  const {
3148
3233
  channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers,
3149
- message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false
3234
+ message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false,
3235
+ seedable = true
3150
3236
  } = options
3237
+ assertSeedableOption(seedable)
3238
+ const effectiveSeedable = seedable && !NON_SEEDABLE_PROTOCOL_CODES.has(resolvedMessageCode(message, code))
3151
3239
  const capacityEgress = this.capacityEgressFor(options)
3152
3240
  const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
3153
3241
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
@@ -3173,7 +3261,8 @@ export class PrivateMessenger {
3173
3261
  content,
3174
3262
  idempotencyKey: normalizedIdempotencyKey,
3175
3263
  useBulkPacing,
3176
- onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
3264
+ seedable: effectiveSeedable,
3265
+ onPreparedSeed: effectiveSeedable ? this.outgoingSeedHandler(channelPubkey) : undefined,
3177
3266
  _getIykcProofs: this.contentKeyLookup()
3178
3267
  })
3179
3268
  } finally { releaseActivity() }
@@ -3183,8 +3272,11 @@ export class PrivateMessenger {
3183
3272
  const {
3184
3273
  channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers,
3185
3274
  message, code, payload, error, content, idempotencyKey, deletionPubkey, createdAt, createdAtMs,
3186
- onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false
3275
+ onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false,
3276
+ seedable = true
3187
3277
  } = options
3278
+ assertSeedableOption(seedable)
3279
+ const effectiveSeedable = seedable && !NON_SEEDABLE_PROTOCOL_CODES.has(resolvedMessageCode(message, code))
3188
3280
  const capacityEgress = this.capacityEgressFor(options)
3189
3281
  const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
3190
3282
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
@@ -3216,22 +3308,25 @@ export class PrivateMessenger {
3216
3308
  createdAt,
3217
3309
  createdAtMs,
3218
3310
  useBulkPacing,
3219
- onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
3311
+ seedable: effectiveSeedable,
3312
+ onPreparedSeed: effectiveSeedable ? (onPreparedSeed || this.outgoingSeedHandler(channelPubkey)) : undefined,
3220
3313
  preparedPublications: prepared.length ? prepared : undefined,
3221
3314
  _getIykcProofs: this.contentKeyLookup()
3222
3315
  })
3223
3316
  } finally { releaseActivity() }
3224
3317
  }
3225
3318
 
3226
- async broadcastRumor ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, rumor, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false }) {
3227
- const channel = this.requireWritableChannel(channelPubkey)
3319
+ async broadcastRumor ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, rumor, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false, seedable = true, capacityEgress, [CAPACITY_EGRESS]: scopedCapacityEgress }) {
3320
+ assertSeedableOption(seedable)
3321
+ const capacityEgressToken = this.capacityEgressFor({ capacityEgress: scopedCapacityEgress || capacityEgress })
3322
+ const channel = this.requireWritableChannel(channelPubkey, { capacityEgress: capacityEgressToken })
3228
3323
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
3229
3324
  try {
3230
3325
  const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
3231
3326
  const receivers = uniq(receiverPubkeys?.length
3232
3327
  ? receiverPubkeys
3233
3328
  : prepared.flatMap(publication => publication.receiverPubkeys || []))
3234
- const routing = await this.resolveSendRouting({ channel, receiverPubkeys: receivers, relays, relayToReceivers, signal, attemptStartedAt, onDebug })
3329
+ const routing = await this.resolveSendRouting({ channel, receiverPubkeys: receivers, relays, relayToReceivers, signal, attemptStartedAt, onDebug, capacityEgress: capacityEgressToken })
3235
3330
  this.debugSend('broadcastRumor', channelPubkey, { receiverPubkeys: receivers })
3236
3331
  return await this._privateMessage.broadcastRumor({
3237
3332
  senderSigner: this.userSigner,
@@ -3246,22 +3341,25 @@ export class PrivateMessenger {
3246
3341
  autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
3247
3342
  rumor,
3248
3343
  useBulkPacing,
3249
- onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
3344
+ seedable,
3345
+ onPreparedSeed: seedable ? (onPreparedSeed || this.outgoingSeedHandler(channelPubkey)) : undefined,
3250
3346
  preparedPublications: prepared.length ? prepared : undefined,
3251
3347
  _getIykcProofs: this.contentKeyLookup()
3252
3348
  })
3253
3349
  } finally { releaseActivity() }
3254
3350
  }
3255
3351
 
3256
- async broadcastEvent ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, event, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false }) {
3257
- const channel = this.requireWritableChannel(channelPubkey)
3352
+ async broadcastEvent ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, event, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false, seedable = true, capacityEgress, [CAPACITY_EGRESS]: scopedCapacityEgress }) {
3353
+ assertSeedableOption(seedable)
3354
+ const capacityEgressToken = this.capacityEgressFor({ capacityEgress: scopedCapacityEgress || capacityEgress })
3355
+ const channel = this.requireWritableChannel(channelPubkey, { capacityEgress: capacityEgressToken })
3258
3356
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
3259
3357
  try {
3260
3358
  const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
3261
3359
  const receivers = uniq(receiverPubkeys?.length
3262
3360
  ? receiverPubkeys
3263
3361
  : prepared.flatMap(publication => publication.receiverPubkeys || []))
3264
- const routing = await this.resolveSendRouting({ channel, receiverPubkeys: receivers, relays, relayToReceivers, signal, attemptStartedAt, onDebug })
3362
+ const routing = await this.resolveSendRouting({ channel, receiverPubkeys: receivers, relays, relayToReceivers, signal, attemptStartedAt, onDebug, capacityEgress: capacityEgressToken })
3265
3363
  this.debugSend('broadcastEvent', channelPubkey, { receiverPubkeys: receivers })
3266
3364
  return await this._privateMessage.broadcastEvent({
3267
3365
  senderSigner: this.userSigner,
@@ -3276,7 +3374,8 @@ export class PrivateMessenger {
3276
3374
  autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
3277
3375
  event,
3278
3376
  useBulkPacing,
3279
- onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
3377
+ seedable,
3378
+ onPreparedSeed: seedable ? (onPreparedSeed || this.outgoingSeedHandler(channelPubkey)) : undefined,
3280
3379
  preparedPublications: prepared.length ? prepared : undefined,
3281
3380
  _getIykcProofs: this.contentKeyLookup()
3282
3381
  })
@@ -3344,7 +3443,7 @@ export class PrivateMessenger {
3344
3443
  code: SEEDER_PRESENCE_CODE,
3345
3444
  payload: {},
3346
3445
  useBulkPacing: true,
3347
- onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
3446
+ seedable: false,
3348
3447
  _getIykcProofs: this.contentKeyLookup()
3349
3448
  })
3350
3449
  }
@@ -3439,7 +3538,9 @@ export class PrivateMessenger {
3439
3538
  ask: scopedMethod('ask'),
3440
3539
  reply: scopedMethod('reply'),
3441
3540
  tell: scopedMethod('tell'),
3442
- yell: scopedMethod('yell')
3541
+ yell: scopedMethod('yell'),
3542
+ broadcastRumor: scopedMethod('broadcastRumor'),
3543
+ broadcastEvent: scopedMethod('broadcastEvent')
3443
3544
  }),
3444
3545
  token,
3445
3546
  release (reason = expiredCapacityEgress()) {
@@ -3650,7 +3751,8 @@ export class PrivateMessenger {
3650
3751
  until,
3651
3752
  ...(priority === 'normal' ? {} : { priority })
3652
3753
  },
3653
- useBulkPacing: priority !== 'normal'
3754
+ useBulkPacing: priority !== 'normal',
3755
+ seedable: false
3654
3756
  })
3655
3757
  await assertMessagePublished(ask, ask.question)
3656
3758
  asks.push(ask)
@@ -232,6 +232,7 @@ export function createEventReplyPacker ({
232
232
  recordsFromInput = eventRecordFromInput,
233
233
  sendEmptyReply = false,
234
234
  useBulkPacing = true,
235
+ seedable = true,
235
236
  idempotencyKey
236
237
  }) {
237
238
  if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
@@ -239,6 +240,7 @@ export function createEventReplyPacker ({
239
240
  if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
240
241
  if (!Number.isSafeInteger(eventsPerChunk) || eventsPerChunk < 1) throw new ValidationError('INVALID_EVENTS_PER_CHUNK')
241
242
  if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
243
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
242
244
  const idempotencyKeyBase = normalizeIdempotencyKeyBase(idempotencyKey)
243
245
 
244
246
  let chunk = ''
@@ -259,6 +261,7 @@ export function createEventReplyPacker ({
259
261
  ? { idempotencyKey: chunkIdempotencyKey(idempotencyKeyBase, index) }
260
262
  : {}),
261
263
  useBulkPacing,
264
+ ...(seedable ? {} : { seedable: false }),
262
265
  payload: {
263
266
  ...payload,
264
267
  index,
@@ -321,6 +324,7 @@ export function createMissingMessageReplyPacker ({
321
324
  bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
322
325
  sendEmptyReply = false,
323
326
  useBulkPacing,
327
+ seedable = false,
324
328
  idempotencyKey
325
329
  }) {
326
330
  if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
@@ -330,6 +334,7 @@ export function createMissingMessageReplyPacker ({
330
334
  if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
331
335
  if (!RECOVERY_PRIORITIES.has(priority)) throw new ValidationError('INVALID_RECOVERY_PRIORITY')
332
336
  if (useBulkPacing !== undefined && typeof useBulkPacing !== 'boolean') throw new ValidationError('INVALID_USE_BULK_PACING')
337
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
333
338
  idempotencyKey ||= `${MISSING_MESSAGES_REPLY_CODE}:${question.id}`
334
339
 
335
340
  const range = backfillRequestRange(question, since, until)
@@ -348,6 +353,7 @@ export function createMissingMessageReplyPacker ({
348
353
  bytesPerChunk,
349
354
  sendEmptyReply,
350
355
  useBulkPacing: useBulkPacing ?? priority !== 'normal',
356
+ seedable,
351
357
  idempotencyKey,
352
358
  recordsFromInput: seed => compactRecordsFromSeed(seed, { receiverPubkey, since: range.since, until: range.until })
353
359
  })
@@ -1,4 +1,5 @@
1
1
  import { run } from '../../idb/index.js'
2
+ import { withRecoverableLock } from '../../helpers/recoverable-lock.js'
2
3
  import { cleanupReceivedChunkStorage } from '../../private-channel/services/received-chunks.js'
3
4
  import { cleanupTemporaryStorage } from '../../temporary-storage/index.js'
4
5
  import { DEFAULT_STALE_CHANNEL_SECONDS } from '../constants/index.js'
@@ -8,12 +9,14 @@ const REGISTRY_VERSION = 1
8
9
  const STORAGE_SETS_STORE = 'storageSets'
9
10
  const LEASES_STORE = 'leases'
10
11
  const LOCK_NAME = 'libp2r2p:private-messenger:storage-maintenance'
12
+ const LOCK_LEASE_MS = 15_000
13
+ const LOCK_HEARTBEAT_MS = 5_000
14
+ const DELETE_DATABASE_BLOCKED_TIMEOUT_MS = 5_000
11
15
  const LEASE_MS = 2 * 60 * 60 * 1000 // 2 hours
12
16
  const DEFAULT_IDENTITY_STORAGE_RETENTION_SECONDS = 60 * 24 * 60 * 60
13
17
  const MAX_RETENTION_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1000)
14
18
  const MAX_RETRY_MS = 5 * 60 * 1000
15
19
 
16
- const localLocks = new WeakMap()
17
20
  const retryTimers = new WeakMap()
18
21
 
19
22
  /*
@@ -167,18 +170,16 @@ function storagePolicy (storageSet) {
167
170
  }
168
171
  }
169
172
 
170
- function withLocalLock (indexedDB, work) {
171
- const prior = localLocks.get(indexedDB) || Promise.resolve()
172
- const next = prior.catch(() => {}).then(work)
173
- localLocks.set(indexedDB, next.catch(() => {}))
174
- return next
175
- }
176
-
177
- function withMaintenanceLock (indexedDB, work) {
173
+ function withMaintenanceLock (indexedDB, work, options = {}) {
178
174
  if (!indexedDB?.open) return Promise.reject(new Error('IDB_UNAVAILABLE'))
179
- const locks = globalThis.navigator?.locks
180
- if (typeof locks?.request === 'function') return locks.request(LOCK_NAME, work)
181
- return withLocalLock(indexedDB, work)
175
+ return withRecoverableLock({
176
+ name: LOCK_NAME,
177
+ work,
178
+ fallbackScope: indexedDB,
179
+ leaseMs: LOCK_LEASE_MS,
180
+ heartbeatMs: LOCK_HEARTBEAT_MS,
181
+ ...options
182
+ })
182
183
  }
183
184
 
184
185
  function storageDatabaseNames (userPubkey) {
@@ -194,27 +195,46 @@ function storageDatabaseNames (userPubkey) {
194
195
  ]
195
196
  }
196
197
 
197
- function deleteDatabase (indexedDB, name) {
198
+ function deleteDatabase (indexedDB, name, { blockedTimeoutMs = DELETE_DATABASE_BLOCKED_TIMEOUT_MS, signal } = {}) {
198
199
  return new Promise(resolve => {
200
+ let settled = false
201
+ let blockedTimer = null
202
+ const finish = value => {
203
+ if (settled) return
204
+ settled = true
205
+ if (blockedTimer != null) clearTimeout(blockedTimer)
206
+ signal?.removeEventListener('abort', onAbort)
207
+ resolve(value)
208
+ }
209
+ const onAbort = () => finish(false)
210
+ if (signal?.aborted) {
211
+ finish(false)
212
+ return
213
+ }
214
+ signal?.addEventListener('abort', onAbort, { once: true })
199
215
  let request
200
216
  try {
201
217
  request = indexedDB.deleteDatabase(name)
202
218
  } catch {
203
- resolve(false)
219
+ finish(false)
204
220
  return
205
221
  }
206
- request.onsuccess = () => resolve(true)
207
- request.onerror = () => resolve(false)
208
- // A blocked delete request remains live and will continue automatically
209
- // after every other connection closes. Keep the maintenance lock until
210
- // that definitive success/error instead of scheduling a second request.
211
- request.onblocked = () => {}
222
+ request.onsuccess = () => finish(true)
223
+ request.onerror = () => finish(false)
224
+ // A blocked delete request stays live for a bounded grace window so a
225
+ // closing handle can finish, without pinning the cross-tab maintenance lock
226
+ // indefinitely if another tab remains open or frozen.
227
+ request.onblocked = () => {
228
+ if (blockedTimer != null) return
229
+ blockedTimer = setTimeout(() => finish(false), blockedTimeoutMs)
230
+ blockedTimer?.unref?.()
231
+ }
212
232
  })
213
233
  }
214
234
 
215
- async function deleteStorageSet (indexedDB, userPubkey) {
235
+ async function deleteStorageSet (indexedDB, userPubkey, options) {
216
236
  const results = await Promise.all(storageDatabaseNames(userPubkey)
217
- .map(name => deleteDatabase(indexedDB, name)))
237
+ .map(name => deleteDatabase(indexedDB, name, options)))
218
238
  return results.every(Boolean)
219
239
  }
220
240
 
@@ -277,10 +297,12 @@ async function finishDeleteAttempt (indexedDB, attempted, deleted, now) {
277
297
  })
278
298
  }
279
299
 
280
- async function maintainRegistry (indexedDB, now) {
300
+ async function maintainRegistry (indexedDB, now, { assertLeader, signal, blockedTimeoutMs } = {}) {
281
301
  const due = await markAndListDueStorageSets(indexedDB, now)
282
302
  for (const storageSet of due) {
283
- const deleted = await deleteStorageSet(indexedDB, storageSet.userPubkey)
303
+ assertLeader?.()
304
+ const deleted = await deleteStorageSet(indexedDB, storageSet.userPubkey, { blockedTimeoutMs, signal })
305
+ assertLeader?.()
284
306
  await finishDeleteAttempt(indexedDB, storageSet, deleted, now)
285
307
  }
286
308
  const nextAttemptAt = await withRegistryTransaction(indexedDB, 'readonly', async tx => {
@@ -314,11 +336,16 @@ function schedulePendingRetry (indexedDB, temporaryStorageArea, nextAttemptAt, n
314
336
  export async function maintainPrivateMessengerStorage ({
315
337
  indexedDB = globalThis.indexedDB,
316
338
  temporaryStorageArea = globalThis.sessionStorage,
317
- now = Date.now()
339
+ now = Date.now(),
340
+ blockedTimeoutMs = DELETE_DATABASE_BLOCKED_TIMEOUT_MS
318
341
  } = {}) {
319
342
  if (temporaryStorageArea) cleanupTemporaryStorage({ storageArea: temporaryStorageArea })
320
343
  await cleanupReceivedChunkStorage({ indexedDB, now })
321
- const result = await withMaintenanceLock(indexedDB, () => maintainRegistry(indexedDB, now))
344
+ const result = await withMaintenanceLock(
345
+ indexedDB,
346
+ ({ assertLeader, signal }) => maintainRegistry(indexedDB, now, { assertLeader, signal, blockedTimeoutMs }),
347
+ { ifAvailableOnly: true, skippedValue: { processed: 0, nextAttemptAt: null } }
348
+ )
322
349
  schedulePendingRetry(indexedDB, temporaryStorageArea, result.nextAttemptAt, now)
323
350
  return result.processed
324
351
  }
@@ -128,8 +128,14 @@ No message eviction or false historical coverage is introduced. Account
128
128
  unavailability stops its recovery timers; availability or explicit retry can
129
129
  reevaluate a local failure without clearing another owner's storage pause.
130
130
 
131
- `enqueue({ peer, event, context, requiredFiles, deletion })` preserves prepared
132
- identities. Local message commits and remote stages have independent checkpoints.
131
+ `enqueue({ peer, event, context, requiredFiles, deletion, allowCapacityEgress })`
132
+ preserves prepared identities. `allowCapacityEgress` defaults to `false` and is
133
+ persisted with the encrypted outbox entry. When true, a remote user message may
134
+ use a fresh `createCapacityEgress()` token while `capacity` is the only pause
135
+ reason. The token covers every context event, file chunk and final event in that
136
+ entry and is recreated on each retry. It never bypasses network, storage, signer,
137
+ session-storage or another simultaneous pause. Local message commits and remote
138
+ stages have independent checkpoints.
133
139
  Recovery archival waits up to five seconds for foreground work, then runs one
134
140
  durable batch and re-evaluates; postponement never drops packet rows.
135
141
  It sends original/thumbnail chunks before announcements, yields for small messages,
@@ -155,6 +161,10 @@ messages. Entering pressure emits one sanitized
155
161
  type/age buckets plus bounded counts by inner message code; it never exposes IDs,
156
162
  pubkeys, filters, ciphertext or payloads.
157
163
  Physical `QUEUE_CAPACITY_EXCEEDED` behavior remains unchanged.
164
+ Capacity-only egress is opt-in per user work item. Protocol asks, replies,
165
+ announcements, presence and recovery traffic remain blocked unless the active
166
+ inbound handler receives the short-lived reservation token created by the
167
+ messenger.
158
168
 
159
169
  Native `AbortError` values represent pause/teardown cancellation. The messenger
160
170
  reports the first occurrence in each 30-second window as