Skip to content

PeerborneDocument

Defined in: packages/core/src/peerborne-document.ts:1295

DocType

ChangesType

ChangeFnType

PrivateKey

PublicKey

DocumentKey

new PeerborneDocument<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>(swarm, documentPath, _userKey, _userPublicKey, _crdtProvider, _authProvider, _aclProvider, _keychainProvider, _changesSerializer, _syncMessageSerializer, _loadMessageSerializer, options?): PeerborneDocument<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>

Defined in: packages/core/src/peerborne-document.ts:2049

Peerborne<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>

Peerborne swarm that this document belongs to.

string

Path of the document.

PrivateKey

Private key identifying the current user.

PublicKey

Private key identifying the current user.

CRDTProvider<DocType, ChangesType, ChangeFnType>

CRDTProvider handles reading/writing CRDT document data and metadata.

AuthProvider<PrivateKey, PublicKey, DocumentKey>

AuthProvider handles signing/verification and encryption/decryption.

ACLProvider<ChangesType, PublicKey>

ACLProvider handles read/write ACL operations.

KeychainProvider<ChangesType, DocumentKey>

KeychainProvider handles read/write ACL operations.

ChangesSerializer<ChangesType>

ChangesSerializer is responsible for serializing/deserializing CRDT changes.

SyncMessageSerializer<ChangesType>

SyncMessageSerializer is responsible for serializing/deserializing CRDTSyncMessages.

LoadMessageSerializer

LoadMessageSerializer is responsible for serializing/deserializing CRDTLoadMessages.

CoordinatedDocumentOptions

PeerborneDocument<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>

readonly documentPath: string

Defined in: packages/core/src/peerborne-document.ts:2065

Path of the document.


readonly swarm: Peerborne<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>

Defined in: packages/core/src/peerborne-document.ts:2053

Peerborne swarm that this document belongs to.

get antiEntropyStatus(): AntiEntropyStatus

Defined in: packages/core/src/peerborne-document.ts:9159

Automatic catch-up state for this document.

AntiEntropyStatus


get competingBeeKEMGeneration(): number | undefined

Defined in: packages/core/src/peerborne-document.ts:1321

Generation at which this instance stopped after observing an authenticated competing BeeKEM tree.

number | undefined


get deliveryFailure(): ChangeDeliveryFailure | undefined

Defined in: packages/core/src/peerborne-document.ts:13027

The latest local change that is committed but not known to have reached a member, as reported to subscribeDeliveryFailures() handlers. It is cleared on evidence that a member holds the change or was sent it: a later local frame or sync response sent to a peer that recently proved it serves a member, a member’s sync request that names the change, or a writer’s frame that names it. A peer proves it serves a member only with a sync request signed by a member’s key that names that peer as its publisher. This is evidence of delivery, not an acknowledgment that a member stored it. A load served to a member is not evidence until the member’s next sync request names the change. A member with automatic catch-up sends that request one to two seconds after a frame adds a change, so a change that reaches members only through a relay clears within a few seconds. Local update handlers see the value after their change. A coordinated document never sets it.

ChangeDeliveryFailure | undefined


get document(): DocType

Defined in: packages/core/src/peerborne-document.ts:1313

The current document. While a batch of remote frames is applied, this is the document from before the batch until every frame in it is settled.

DocType


get historyVisibility(): HistoryVisibility

Defined in: packages/core/src/peerborne-document.ts:1738

HistoryVisibility

set historyVisibility(value): void

Defined in: packages/core/src/peerborne-document.ts:1732

Set the history visibility for this document. This filters distributed epoch keys; it does not redact retained CRDT operations or provide a historical-content confidentiality boundary.

HistoryVisibility

void


get invitationEpoch(): Uint8Array<ArrayBufferLike> | undefined

Defined in: packages/core/src/peerborne-document.ts:16434

Test/inspection helper: returns a copy of the recorded invitation epoch, or undefined if no Welcome has been processed (e.g. founding member). The returned Uint8Array is a defensive copy so external callers cannot mutate the document’s internal state and alter subsequent since_invited filtering behavior.

Uint8Array<ArrayBufferLike> | undefined


get latestSnapshot(): CRDTSnapshotNode<ChangesType> | undefined

Defined in: packages/core/src/peerborne-document.ts:14135

Returns the current snapshot, if one exists.

CRDTSnapshotNode<ChangesType> | undefined


get libp2p(): Libp2p

Defined in: packages/core/src/peerborne-document.ts:2043

Libp2p


get pendingWelcomesCount(): number

Defined in: packages/core/src/peerborne-document.ts:16411

Internal

Test/inspection helper: number of BeeKEM Welcomes currently parked in the pending-welcomes buffer awaiting a readers-ACL update.

exposed only for unit tests.

number


get pendingWelcomesRetainedBytes(): number

Defined in: packages/core/src/peerborne-document.ts:16422

Internal

Test/inspection helper: exact number of serialized Welcome bytes retained by the pending-welcomes buffer.

exposed only for unit tests.

number


get readerRevocationCount(): number

Defined in: packages/core/src/peerborne-document.ts:1612

Internal

Number of completed reader revocations. Invitation offers issued before a revocation cannot claim the collaborator slot it frees.

number


get retired(): boolean

Defined in: packages/core/src/peerborne-document.ts:1331

Whether this instance was retired and refuses further work: after an oversized edit, a failed change it could not roll back, or a failure that left its authorization state indeterminate. Continue with a fresh instance opened from accepted state, such as the last checkpoint.

boolean


get securityCatchUpStaleRequests(): number

Defined in: packages/core/src/peerborne-document.ts:10851

Topic catch-up requests sealed under the current epoch key and ignored because their issue time was more than 60 s from this node’s clock.

number


get securityRedeliveryStaleRequests(): number

Defined in: packages/core/src/peerborne-document.ts:11084

Redelivery requests sealed under the current epoch key and ignored because their issue time was more than 60 s from this node’s clock. Redelivery needs clocks within that range.

number

acceptInvitationBootstrap(bundle, issuerPublicKey, role, founderAddress): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:15388

Internal

Apply a recipient-bound invitation bootstrap and activate the document without invoking normal first-load/new-document detection.

The outer invitation acceptance must be verified against issuerPublicKey before this method is called. This method independently verifies the enclosed bootstrap signature against that exact key. It may only run on the reserved candidate created by Peerborne.acceptInvitation; failures discard that unexposed instance rather than returning partial provider state to application code.

InvitationBootstrapBundle

PublicKey

"reader" | "editor"

string

Promise<void>


addChange(changeFn): void

Defined in: packages/core/src/peerborne-document.ts:13094

Queue a change function within an active transaction. Must be called between startChange() and endChange().

ChangeFnType

void


addReader(reader, readerKemPublicKey): Promise<BeeKEMWelcomeV2>

Defined in: packages/core/src/peerborne-document.ts:14682

Resend the BeeKEM Welcome to an identity that is already an explicit reader. Users are identified by their public keys.

addReader cannot onboard a new identity. A recipient that has only a KEM key pair cannot authenticate a broadcast Welcome or decrypt the reader ACL row that would admit it, so it could never open the document, while its row would occupy the single collaborator slot. Any identity that is not already a reader is therefore rejected before ACL or BeeKEM state changes. Share a document with another identity through createInvitation() and the recipient’s Peerborne.acceptInvitation().

For an existing reader, this re-sends the cached recipient-bound Welcome with the keychain changes appropriate for the document’s historyVisibility setting and the current epoch ID. The Welcome is delivered via the beekemWelcomeV2 protocol to every currently-connected peer; the receiving document ignores Welcomes addressed to a different reader.

CONFIDENTIALITY: the Welcome’s keychain delta is sealed with ECIES (P-256 ECDH + AES-256-GCM) under readerKemPublicKey, so only the intended recipient can decrypt it. The recipient binding (welcomeRecipient) is the authorization gate; the sealed payload is the confidentiality gate. See _sendBeeKEMWelcome for the full construction.

PublicKey

An existing reader’s identity (signing) public key.

Uint8Array

Raw SEC1-uncompressed P-256 ECDH public key (65 bytes) bound to that reader when it joined. The reader must hold the matching private key (see setKemKeyPair). The Welcome is sealed to this key; the library never broadcasts an un-sealed Welcome.

Promise<BeeKEMWelcomeV2>

The BeeKEM Welcome used for this reader.

If reader is not already an explicit reader.


addWriter(writer): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:14378

Grant write authorization to an existing explicit reader. Users are identified by their public keys. The target must already be a reader, normally through a reader invitation, so a later removeWriter() can safely return them to read-only access without misrepresenting retained document-key access as revocation.

Promotion also requires the target’s identity-bound reader KEM public key and a matching live BeeKEM leaf. The founder document records that binding when the invitation onboards the reader, and its checkpoints carry it across restarts. Requires AuthProvider.serializePublicKey.

The local ACL commits only after GossipSub publication resolves. A rejected publish rolls back local DAG bookkeeping, but transport rejection is delivery-ambiguous: a remote peer may already have received the delta. This is a local publication boundary, not a distributed transaction.

PublicKey

User’s public key

Promise<void>


applySecurityAuthorityUpdate(encoded): Promise<CoordinatedAuthorityUpdateResult>

Defined in: packages/core/src/peerborne-document.ts:11012

Apply a controller-signed role update. At a new group context, this author’s unsent frames from the retired context are re-signed and sent when it can still write them, and removed otherwise.

Uint8Array

Promise<CoordinatedAuthorityUpdateResult>


applySecurityAuthorityUpdateBeforeOpen(encoded): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:11031

Apply a controller-signed role update matching the authenticated group state before opening a fresh strict coordinated document. The instance reserves its local document path until it closes.

Uint8Array

Promise<void>


applySecurityCatchUpCheckpoint(checkpoint): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:10963

Durably merge a solicited current-controller checkpoint with accepted local state.

Uint8Array

Promise<void>


assertBeeKEMForkAdmission(): void

Defined in: packages/core/src/peerborne-document.ts:2289

Internal

Recheck an invitation response at its dispatch boundary.

void


assertCanCreateInitialInvitation(): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:1551

Internal

Validate the deliberately narrow initial membership topology.

Promise<void>


buildInvitationBootstrap(reader, readerKemPublicKey, role, assertCanMutate?, assertCanContinue?): Promise<InvitationBootstrapBundle>

Defined in: packages/core/src/peerborne-document.ts:14966

Internal

Grant an invitation recipient access and construct the encrypted material returned by the invitation join protocol. The caller is responsible for signing the outer acceptance and enforcing single-use offer semantics. Membership work is not transactional: an error after mutation begins can leave partial or complete recipient membership without a returned bundle. Only an exact, same-process retry is eligible to complete and attest that state. It publishes only the membership deltas that are still missing; committed ACL nodes reach the recipient through the signed bootstrap tree. assertCanMutate guards the first membership mutation. assertCanContinue guards the remaining checkpoints and defaults to assertCanMutate, so a retry whose membership is already committed can use a weaker guard.

PublicKey

Uint8Array

"reader" | "editor"

() => void

(() => void) | undefined = assertCanMutate

Promise<InvitationBootstrapBundle>


change(changeFn, message?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:13229

Applies a new local change (defined by changeFn) to the peerborne document and updates all peers. If changeFn throws, the call rejects. A coordinated document (peerborne.doc(path, { security })) stages the edit on a private copy, so the document is unchanged and nothing is published. Otherwise Automerge discards the edit, and an in-place provider (Yjs, Loro) publishes the edits made before the throw and then rethrows the original error. If committing that partial edit fails too, an AggregateError holds the change function’s error and the commit error. The call rejects with it when the partial edit was kept, as described below, and otherwise retires the instance with it as the cause.

The change is committed locally once its block is stored and it is in the retained change tree. When encrypting or publishing its frame then fails, for example because GossipSub has no topic peers, or the frame reaches no member’s peer, the call still resolves: the change stays in the document, the next change’s frame carries it inline, and sync and load responses serve it. The failure is reported to subscribeDeliveryFailures() handlers. A failure from a local update handler or compaction rejects the call but also keeps the change.

A frame that outgrows GossipSub only because of the retained history is first compacted and published again. A failure before that point (block storage, signing or the frame size check) discards the change, so no later change depends on an edit peers never received. The attempt’s history bookkeeping is removed. Automerge outdates the document a change consumes, so the document before the call is restored as a writable copy from CRDTProvider.cloneDocument(), which makes later changes under a new actor. An in-place provider (Yjs, Loro) cannot undo its edit, Automerge cannot copy a document that holds remote changes waiting for missing dependencies, and a change that fails after that compaction is already in its snapshot. In those cases the instance is retired: the call rejects with an error whose cause is the failure, and the instance refuses further work until it is reopened from accepted state, such as the last checkpoint exported before the failure. A change too large for one frame retires the instance with a GossipFrameLimitError instead.

ChangeFnType

A function that makes changes to the current CRDT document.

string

An optional change message/description to include.

Promise<void>


close(): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:11756

Disconnects from this peerborne document. Running this method disconnects from the document pubsub topic.

Multiple open PeerborneDocument instances sharing the same documentPath are not supported. Cleanup is instance-safe, so a failed or stale instance does not unregister a newer live document.

Promise<void>


collectGarbage(): Promise<Readonly<{ pending: number; }>>

Defined in: packages/core/src/peerborne-document.ts:14218

Retry bounded local GC work without creating a new snapshot.

Promise<Readonly<{ pending: number; }>>


create(): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:10633

Create a new document under an application-owned path without querying peers. Rejects a path that this node already created or holds open, and an instance with restored or loaded state: open that path instead, since creating it again would found a different document with a new key.

Promise<boolean>


createInvitation(options): Promise<InvitationOfferV1>

Defined in: packages/core/src/peerborne-document.ts:1541

Create a signed public offer for an online, distinct-identity join. The offer contains only public metadata and is safe to encode in a URL fragment. The inviter must remain online until the recipient accepts it. The founder can invite again after removeReader revokes its only collaborator; each completed removeReader invalidates every offer issued before it.

CreateInvitationOptions

Promise<InvitationOfferV1>


createSecurityCatchUpCheckpoint(request): Promise<Uint8Array<ArrayBufferLike>>

Defined in: packages/core/src/peerborne-document.ts:10956

Answer an authenticated current member’s request with an encrypted checkpoint.

Uint8Array

Promise<Uint8Array<ArrayBufferLike>>


createSecurityCatchUpRequest(): Promise<Uint8Array<ArrayBufferLike>>

Defined in: packages/core/src/peerborne-document.ts:10951

Create an encrypted request for the current controller to relay through the application.

Promise<Uint8Array<ArrayBufferLike>>


endChange(message?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:13125

End the transaction and apply all queued changes atomically. This sends a single sync message for all batched changes.

A failure is handled as in change(): once the batch is stored and in the retained change tree it is kept, and an encryption or publication failure is reported to subscribeDeliveryFailures() handlers instead of rejecting. A batch that fails before that point is discarded. Either way the transaction ends, and a new one must be started.

A queued change function that throws is handled as in change(): a coordinated document stages the batch on a private copy and leaves the document unchanged. Otherwise Automerge discards the batch, and an in-place provider (Yjs, Loro) publishes the edits made before the throw as this transaction’s change and then rethrows the original error, so no later change depends on an unpublished edit. If committing that partial edit fails too, the call rejects as change() does.

string

Promise<void>

If any step in the commit pipeline fails.


exportEncryptedCheckpoint(storageKey): Promise<Uint8Array<ArrayBufferLike>>

Defined in: packages/core/src/peerborne-document.ts:10154

Capture a bounded, self-signed local checkpoint, encrypted with AES-GCM under storageKey and bound to this document path. Restore it with restoreEncryptedCheckpoint() and the same key before open(). Use a non-extractable 256-bit AES-GCM key that the application keeps apart from the checkpoint. The checkpoint is local recovery, not a network trust or backup format: it holds document keys, so never send it to another party.

CryptoKey

Promise<Uint8Array<ArrayBufferLike>>


exportPlaintextCheckpoint(): Promise<DocumentCheckpoint>

Defined in: packages/core/src/peerborne-document.ts:10182

Capture a bounded, self-signed local checkpoint as plaintext. The payload is unencrypted binary holding this document’s state and its raw document keys. Never store it unencrypted and never transmit it; use exportEncryptedCheckpoint() unless the application encrypts it at once with its own authenticated storage format. A state larger than MAX_DOCUMENT_CHECKPOINT_BYTES rejects with DocumentCheckpointLimitError. Local changes wait only while the state is captured, not while the checkpoint is signed, and exports resolve in the order they captured the state.

Promise<DocumentCheckpoint>


getKemPublicKeyRaw(): Uint8Array<ArrayBufferLike> | undefined

Defined in: packages/core/src/peerborne-document.ts:1529

Returns the raw SEC1-uncompressed bytes (65 bytes) of the installed ECDH public key, or undefined if no key pair has been set via setKemKeyPair.

The raw bytes are cached on setKemKeyPair, so this is a synchronous lookup. A defensive copy of the cached Uint8Array is returned so callers cannot accidentally mutate the document’s internal state (e.g. raw[0] = ...), which would otherwise cause hard-to-debug Welcome drops/mismatches on the receive path.

Uint8Array<ArrayBufferLike> | undefined


getReaders(): Promise<PublicKey[]>

Defined in: packages/core/src/peerborne-document.ts:14611

Returns a list of all public keys with read access.

Deduplicates users that appear in both reader and writer ACLs, which can occur due to concurrent edits or manual addition to both lists.

Promise<PublicKey[]>

List of public keys with read access.


getWriters(): Promise<PublicKey[]>

Defined in: packages/core/src/peerborne-document.ts:14351

Get list of writers.

Promise<PublicKey[]>

List of public keys with write access.


handleBeeKEMPathUpdateRequestData(payload, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:17165

Internal

Handle an inbound beekemPathUpdateV2 payload (already de-framed of the path-prefix header by the shared handler in peerborne.ts).

Validates the writer signature, deserializes the carried PathUpdateV2, applies it to the local BeeKEM tree via processPathUpdate, and installs the resulting document key under the supplied epoch ID. Mirrors the wire framing used by handleBeeKEMWelcomeRequestData.

SECURITY: the writer signature is always verified, regardless of the swarm-wide enableSigning toggle. An unsigned or invalid-signature PathUpdateV2 is dropped without applying any state change. The receiver also validates that the epoch ID it derives locally matches the sender’s pathUpdateEpochId — a mismatch indicates either a peer with stale local BeeKEM state or a tampered payload, and is treated as a hard error.

Invoked by the shared protocol handler in peerborne.ts.

Uint8Array

SharedProtocolHandlerAdmission

Promise<void>


handleBeeKEMWelcomeRequestData(payload, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:15934

Internal

Handles an incoming BeeKEM Welcome message with pre-read payload. Called by the shared protocol handler in Peerborne after the document path header has been stripped and the document looked up in the registry.

Verifies the writer signature on the message, merges the included keychain changes so future blocks can be decrypted, and records the welcomeEpochId as _invitationEpoch so subsequent since_invited history responses are correctly filtered.

Uint8Array

The serialized sync message (without the document path header that the shared handler already stripped).

SharedProtocolHandlerAdmission

Promise<void>


handleInvitationCatchUpRequestData(message, stream, admission?, beforeResponse?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:4863

Internal

Answer an invitation catch-up. beforeResponse runs after the response state is captured and before it is sent; the response is declined when it rejects.

CRDTLoadRequest

ProtocolWriteStream

SharedProtocolHandlerAdmission

() => Promise<void>

Promise<void>


handleLoadRequestData(message, stream, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:4846

CRDTLoadRequest

ProtocolWriteStream

SharedProtocolHandlerAdmission

Promise<void>


handleSecurityAdvertiseRequestData(message, stream, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:7051

Internal

Handles an initial-load quorum security-advertise request with pre-read stream data. Called by the shared protocol handler in Peerborne after reading and routing.

Closes the “no quorum protocol for verifying initial document state” gap tracked under issue #189 §5.4 item 2 (also bulleted in #186). The wire protocol is securityAdvertiseV1 (see wire-protocols.ts); this method returns either an empty payload (decline) or an encrypted CRDTSyncMessage whose only populated payload field is tipsHash. The loader on the other side compares hashes across multiple peers and requires Q-of-K agreement before accepting any peer’s full document state. See load-quorum.ts for the decision logic.

Authorization mirrors the doc-load / snapshot-load handlers: when signing is enabled the requester must sign the document path with a key that appears in the readers or writers ACL. The response is encrypted under the document’s current key so a peer that does not already possess the key cannot use the tip hash as an oracle (key delivery is handled by the BeeKEM Welcome path).

CRDTLoadRequest

The deserialized load request (already parsed by the shared handler).

ProtocolWriteStream

The stream object for sending the response.

SharedProtocolHandlerAdmission

Promise<void>


handleSnapshotLoadRequestData(message, stream, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:6927

Internal

Handles a snapshot-load request with pre-read stream data. Called by the shared protocol handler in Peerborne after reading and routing.

CRDTLoadRequest

The deserialized load request (already parsed by the shared handler).

ProtocolWriteStream

The stream object for sending the response.

SharedProtocolHandlerAdmission

Promise<void>


hasChange(cid): boolean

Defined in: packages/core/src/peerborne-document.ts:14198

Check whether a CID is known to this document (i.e. present in the in-memory _hashes set). Useful for callers that want to confirm a change exists before attempting a lazy load.

Note: returning true only proves the CID has been observed (it is tracked in _hashes for sync-message dedup). It does NOT guarantee the underlying block is locally available — after gcAfterPrune runs, the CID can remain in _hashes even though the block has been removed from the blockstore. Callers should therefore still handle loadChangeBlock(cid) resolving to undefined (and may need to fall back to dialing peers). _hashes is bounded: a CID outside the retained tree, the snapshot boundary, the recent tips and the newest frontier heads is forgotten once roughly 1,024 to 2,048 newer CIDs are known, after which this returns false.

string

boolean


historySize(): number

Defined in: packages/core/src/peerborne-document.ts:14127

Returns the total number of change nodes (including ACL nodes) tracked in the current document history. This is a count of all known CIDs, not the depth of the longest path in the DAG.

number


invitationCheckpointMark(): string

Defined in: packages/core/src/peerborne-document.ts:14947

Internal

Identifies the changes this instance holds: it changes whenever a change is recorded, so a checkpoint exported after it was read holds every change a response captured while it is unchanged.

string


load(preferredPeer?, signal?): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:8837

Load existing state using the current V4 protocol. Before network requests, capture a fresh challenge, canonical trusted writer authorities, and locally resolved control/group commitments. A first load requires resolveTrustedDocumentWriters; every normal load requires resolveLoadSecurityCommitments. A remote response cannot supply its own trust root. Signing is mandatory.

Quorum selection counts each authenticated authority once. When the captured trusted writer set has exactly one authority, a valid response from any of its devices is accepted without a second vote; devices that advertise different states are tried, most-advertised state first, each bound to its own digest. The selected response must match the captured challenge and tuple, and its derived frontier and manifest must match the bound digest, before mutation. A first load also checks, before mutation, that a writer its writer blocks establish signed its snapshot. Quorum loads prefetch the served tree’s CIDs before applying state. With loadQuorumEnabled false, one trusted signed V4 response may be selected; challenge, tuple, signature, and frontier checks still apply.

string | PeerId

Optional peer to try first (typically a PeerId from a pubsub message sender), matched against the last /p2p/<id> segment of each connection’s multiaddr.

AbortSignal

Optional cancellation. Once it aborts, no further peer is tried and an in-flight response stops before it applies more state.

Promise<boolean>

true after successful loading; false if no usable response is available without a quorum decision. Neither result authorizes creation.

If required agreement or bound delivery fails.

If no peer served the document and a response was discarded because writer authorization changed while it was being applied. The load can be retried.

If trust configuration is absent or bootstrap application left incomplete state. Discard an instance with incomplete application.


loadChangeBlock(cid): Promise<ChangesType | undefined>

Defined in: packages/core/src/peerborne-document.ts:14167

Lazy-load a historical change block by CID.

Used to fetch change data on demand for history-visibility consumers (e.g. audit UI, diff viewers) when the change has been pruned from the in-memory sync tree but the block is still present in the Helia blockstore. The returned ChangesType is the deserialized, decrypted payload. With a provider that has an actorBinding, a document change carries its authored-change envelope, which actorBinding.detach() separates.

Returns undefined when:

  • The CID is not in _hashes: this document never saw the change, or forgot it after it left the retained tree (see hasChange).
  • The block is missing from the blockstore (e.g. it was GC’d locally and no peer has re-served it yet). Callers that need stronger guarantees can fall back to dialing peers via the existing sync protocols.

Throws when:

  • The CID is malformed.
  • The block is present locally but decryption fails (wrong/missing keychain entry) or the payload fails to deserialize (corrupted data). These are treated as hard errors so callers can distinguish a recoverable “missing block” condition from a stronger data-integrity issue.

string

CID string of the change block to load.

Promise<ChangesType | undefined>

The deserialized change payload, or undefined if unavailable.


open(): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:9126

Open an existing document, or activate verified invitation state. A failed or empty load never creates a document. Use create() with an application-owned path to explicitly authorize founding a new document.

Promise<boolean>

true when existing state is activated.

If state cannot be loaded or another activation is running.


provisionBeeKEMForkStore(): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:2283

Explicitly enroll a new local BeeKEM scope before any use of this path.

Promise<boolean>


receiveSecurityFrame(frame): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:10762

Accept only the encrypted, signed coordinator document format.

Uint8Array

Promise<boolean>


releaseActor(actor): void

Defined in: packages/core/src/peerborne-document.ts:13422

Stop accepting local changes under an actor from reserveActor().

string

void


removeReader(reader): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:16480

Remove a user as a valid reader. Users are identified by their public keys.

The target must first be downgraded from writer. Revocation resolves the target’s identity-bound KEM key to one unique live BeeKEM leaf, stages any reader-ACL delta, and performs the tree rotation on a clone. An already absent ACL row does not suppress a still-live leaf: the cryptographic removal proceeds.

The new local epoch key is staged before publication. Every participating provider must supply a commit claim: all fallible work finishes before publication, then captured nonthrowing finalizers install ACL, keychain, tree, and identity-cache state in one synchronous turn. A publication failure after valid claims leaves compliant providers on their original state. An invoked claim that throws or returns a malformed/asynchronous record, or a finalizer that throws or returns a value, violates the provider contract and poisons this document instance because partial application cannot be ruled out.

PathUpdateV2 delivery remains best effort after the local transition. A surviving member that misses it needs an explicit recipient-bound recovery or re-invitation; an ordinary load is encrypted under the unknown new key. BeeKEM state is not persisted across restarts. These are cooperative local-API invariants. Incoming raw ACL deltas are not yet checked against replicated identity/KEM transition records.

PublicKey

User’s public key.

Promise<void>

If the BeeKEM tree has no record of this reader (e.g. addReader did not seed a leaf for them, or BeeKEM membership was lost). Callers must surface this rather than silently degrading: a removeReader that “succeeded” without rotating the key would leave the removed reader with full ongoing access.

If identity/KEM/tree state is missing or divergent, a required commit claim is unavailable, or ACL publication fails.

If the target is not an explicit reader and has no identity-bound KEM or leaf record, unless the live BeeKEM tree holds only the local leaf. Removing a non-member is not a no-op while any remote leaf remains, because the absent records cannot prove it was revoked.


removeWriter(writer, options?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:14508

Remove a user’s explicit write authorization while preserving their explicit reader authorization. A writer without explicit reader membership is rejected: this operation does not rotate document keys, so silently removing its only ACL row would misrepresent retained read access as full revocation. To fully revoke an editor, first downgrade it here, then call removeReader so the reader-removal flow rotates the BeeKEM epoch.

The local ACL commits only after GossipSub publication resolves. A rejected publish rolls back local DAG bookkeeping, but transport rejection is delivery-ambiguous: a remote peer may already have received the delta. This is a local publication boundary, not a distributed transaction.

PublicKey

User’s public key

RemoveWriterOptions

Set requireRemainingWriter to reject removal of the last writer with LastWriterRemovalError.

Promise<void>


requestSecurityCatchUp(): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:10822

Ask the current controller, on the document topic, for an encrypted checkpoint, which this document merges when it arrives. Requests also go out automatically when a member opens without content or a role update reaches it without content, and when frames stay held after a redelivery request brought none of them in. While no checkpoint arrives, requests back off from 5 s to 2 min. A request is bound to this node’s libp2p PeerId, which GossipSub signs as its sender. After the controller refuses a request, automatic requests stop until this is called again.

Promise<void>


requestSecurityRedelivery(): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:11088

Promise<void>


requestSync(): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:9288

Ask current members for missed updates using the existing authenticated local membership. Automatic catch-up (antiEntropy in the Peerborne config) sends the same request without an application call.

Promise<void>


reserveActor(): Promise<string | undefined>

Defined in: packages/core/src/peerborne-document.ts:13409

Register a fresh actor for a separate editing copy of this document, such as an editor mirror whose operations later enter through change(). Returns the provider’s native actor identifier, or undefined when the provider does not bind actors. Release it with releaseActor() when the copy is discarded. An instance holds at most 64 reservations and refuses another until one is released.

Promise<string | undefined>


restoreEncryptedCheckpoint(sealed, storageKey, expectedCommitment?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:10355

Restore a checkpoint from exportEncryptedCheckpoint() on a fresh instance, before open(). It must be sealed under storageKey for this document path and signed by this identity. Supply the independently trusted commitment that documentCheckpointCommitment computed from these bytes to restrict restoration to that exact checkpoint.

Uint8Array

CryptoKey

Uint8Array<ArrayBufferLike>

Promise<void>


restorePlaintextCheckpoint(checkpoint, expectedCommitment?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:10398

Restore this identity’s authenticated plaintext checkpoint from exportPlaintextCheckpoint() on a fresh instance. All fallible decoding/provider work is staged before any live state changes. The next open activates the restored local state without a network load. Supply the independently trusted commitment from documentCheckpointCommitment to restrict restoration to that exact state. Applications must protect the pin and keep it current independently of the checkpoint. A signature alone cannot establish freshness.

DocumentCheckpoint

Uint8Array<ArrayBufferLike>

Promise<void>


retrySecurityPublications(): Promise<SecurityPublicationReport>

Defined in: packages/core/src/peerborne-document.ts:11218

Retry durable encrypted publications without running local change callbacks again. Publications that reach no topic peer stay queued, and later local changes join the last of them. A publication sealed for an earlier group context or authority head is never sent, since no current member can accept it. It stays queued while its author can still re-sign its frames into the current context, and is otherwise dropped and counted; the security option onPublicationsDropped hears about every drop, including those of background retries.

Promise<SecurityPublicationReport>


revokeUnacceptedInvitationMember(recipient): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:16720

Internal

Revoke an invitation claimant whose acceptance was never produced. It never received the document key from that invitation, so the revocation frees the collaborator slot. Only a claimant that this replica onboarded is touched: it must hold a local KEM binding that resolves to a live remote leaf of this replica’s tree, and every removal precondition is checked before the demotion, in the same queued operation.

PublicKey

Promise<void>


setKemKeyPair(keyPair): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:1485

Install the ECDH (P-256) key pair that seeds the founder’s BeeKEM leaf and opens BeeKEM Welcome sealed payloads addressed to this user. The application is responsible for persisting and re-supplying this key pair across sessions. A founder installs it before createInvitation; an invitation recipient supplies its pair to acceptInvitation instead.

Idempotent: calling with the same key pair more than once is fine. Pass undefined to clear (subsequent Welcomes will be dropped).

Validation: the key pair MUST be an ECDH P-256 pair, and the private key MUST have 'deriveBits' in its key usages so eciesOpen can perform the ECDH step. The public key MUST be raw-exportable (the inviter-side flow ships those bytes as the welcomeRecipientKemPublicKey field). Mismatches are rejected here with a descriptive error rather than silently accepted and surfaced as a generic WebCrypto failure later in the Welcome receive path.

Async because it eagerly exports the public key to raw bytes via crypto.subtle.exportKey and caches them for the receive path.

CryptoKeyPair | undefined

Promise<void>


snapshot(): Promise<CRDTSnapshotNode<ChangesType> | undefined>

Defined in: packages/core/src/peerborne-document.ts:14213

Creates a snapshot of the current document state.

The snapshot compacts all current change nodes into a single state representation. Requires CRDTProvider.getSnapshot() to be implemented.

Promise<CRDTSnapshotNode<ChangesType> | undefined>

The created snapshot node, or undefined if the provider does not support snapshots.

If the current user does not have write access to this document. Only writers are authorized to create snapshots.


startChange(): void

Defined in: packages/core/src/peerborne-document.ts:13081

Start a change transaction. Changes made via addChange() will be batched and applied atomically when endChange() is called.

void


subscribe(id, handler, originFilter?): void

Defined in: packages/core/src/peerborne-document.ts:12959

Subscribes a change handler to the document. Use this method to receive real-time updates to the document.

string

A unique id for this handler. Used to unsubscribe this handler.

PeerborneDocumentChangeHandler<DocType, PublicKey>

A function that is called when a change is received.

"local" | "all" | "remote" = 'all'

Determines what kinds of change events trigger the handler. ‘remote’ indicates that the change was received from a remote peer. ‘local’ indicates that the change was received from the local document. ‘all’ indicates that all changes should be handled.

void


subscribeDeliveryFailures(id, handler): void

Defined in: packages/core/src/peerborne-document.ts:13002

Subscribe to local changes that were committed but not delivered, because encrypting or publishing their frame failed, for example when GossipSub has no topic peers and does not allow publishing to none. A frame that is published but reaches no peer known to serve a member, as by default with no topic peers or only a relay, is reported with a NoDeliveryPeersError. change() and endChange() still resolve for such a change: it stays in the document, and it reaches peers with the next change’s frame or a sync or load response. Do not repeat the edit. A coordinated document reports a delivery failure by rejecting instead, and does not call these handlers.

Until a member receives it, the change exists only on this device. Export a checkpoint after a delivery failure: if the instance is later retired, it is reopened from the last checkpoint, and an undelivered change made after that checkpoint is lost.

string

An id to remove the handler with unsubscribeDeliveryFailures(id).

PeerborneDocumentDeliveryFailureHandler

Called synchronously with each delivery failure. A thrown error or rejected promise is logged and does not affect the change.

void


subscribeDeliveryState(id, handler): void

Defined in: packages/core/src/peerborne-document.ts:13038

Call handler with deliveryFailure each time it is set or cleared.

string

An id to remove the handler with unsubscribeDeliveryState(id).

PeerborneDocumentDeliveryStateHandler

Called synchronously. A thrown error or rejected promise is logged and does not affect the document.

void


subscribeToAntiEntropy(handlerId, handler): void

Defined in: packages/core/src/peerborne-document.ts:9169

Observe automatic catch-up: detected gaps, requests, loads and repairs. Handlers run in a microtask after the event and cannot interrupt it.

string

An identifier used to unsubscribe the handler later.

AntiEntropyHandler

void


sync(message): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:11866

Given a sync message containing a list of hashes:

  • Fetch new changes that are only hashes (missing change itself) from the blockstore (using the hash).
  • Apply new changes to the existing CRDT document.

OrdinarySyncMessage<ChangesType>

A sync message to apply.

Promise<boolean>

true if the message was applied successfully, false if rejected due to auth failure.

BREAKING CHANGE: Return type changed from Promise<void> to Promise<boolean>. TypeScript callers with explicit Promise<void> type annotations will need to update. Callers should now check the returned boolean to determine whether the message was applied successfully. The former public verifySignature bypass was also removed; ordinary sync always verifies signatures when signing is enabled. Protocol handlers that already verified a specialized message use an internal boundary.


unsubscribe(id): void

Defined in: packages/core/src/peerborne-document.ts:13065

Unsubscribes a change handler from the document.

string

The id of the handler to unsubscribe.

void


unsubscribeDeliveryFailures(id): void

Defined in: packages/core/src/peerborne-document.ts:13056

Remove a handler added with subscribeDeliveryFailures().

string

The id the handler was subscribed with.

void


unsubscribeDeliveryState(id): void

Defined in: packages/core/src/peerborne-document.ts:13047

Remove a handler added with subscribeDeliveryState().

string

void


unsubscribeFromAntiEntropy(handlerId): void

Defined in: packages/core/src/peerborne-document.ts:9176

string

void