PeerborneDocument
Defined in: packages/core/src/peerborne-document.ts:913
Type Parameters
Section titled “Type Parameters”DocType
Section titled “DocType”DocType
ChangesType
Section titled “ChangesType”ChangesType
ChangeFnType
Section titled “ChangeFnType”ChangeFnType
PrivateKey
Section titled “PrivateKey”PrivateKey
PublicKey
Section titled “PublicKey”PublicKey
DocumentKey
Section titled “DocumentKey”DocumentKey
Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”new PeerborneDocument<
DocType,ChangesType,ChangeFnType,PrivateKey,PublicKey,DocumentKey>(swarm,documentPath,_userKey,_userPublicKey,_crdtProvider,_authProvider,_aclProvider,_keychainProvider,_changesSerializer,_syncMessageSerializer,_loadMessageSerializer):PeerborneDocument<DocType,ChangesType,ChangeFnType,PrivateKey,PublicKey,DocumentKey>
Defined in: packages/core/src/peerborne-document.ts:1441
Parameters
Section titled “Parameters”Peerborne<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>
Peerborne swarm that this document belongs to.
documentPath
Section titled “documentPath”string
Path of the document.
_userKey
Section titled “_userKey”PrivateKey
Private key identifying the current user.
_userPublicKey
Section titled “_userPublicKey”PublicKey
Private key identifying the current user.
_crdtProvider
Section titled “_crdtProvider”CRDTProvider<DocType, ChangesType, ChangeFnType>
CRDTProvider handles reading/writing CRDT document data and metadata.
_authProvider
Section titled “_authProvider”AuthProvider<PrivateKey, PublicKey, DocumentKey>
AuthProvider handles signing/verification and encryption/decryption.
_aclProvider
Section titled “_aclProvider”ACLProvider<ChangesType, PublicKey>
ACLProvider handles read/write ACL operations.
_keychainProvider
Section titled “_keychainProvider”KeychainProvider<ChangesType, DocumentKey>
KeychainProvider handles read/write ACL operations.
_changesSerializer
Section titled “_changesSerializer”ChangesSerializer<ChangesType>
ChangesSerializer is responsible for serializing/deserializing CRDT changes.
_syncMessageSerializer
Section titled “_syncMessageSerializer”SyncMessageSerializer<ChangesType>
SyncMessageSerializer is responsible for serializing/deserializing CRDTSyncMessages.
_loadMessageSerializer
Section titled “_loadMessageSerializer”LoadMessageSerializer is responsible for serializing/deserializing CRDTLoadMessages.
Returns
Section titled “Returns”PeerborneDocument<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>
Properties
Section titled “Properties”documentPath
Section titled “documentPath”
readonlydocumentPath:string
Defined in: packages/core/src/peerborne-document.ts:1457
Path of the document.
readonlyswarm:Peerborne<DocType,ChangesType,ChangeFnType,PrivateKey,PublicKey,DocumentKey>
Defined in: packages/core/src/peerborne-document.ts:1445
Peerborne swarm that this document belongs to.
Accessors
Section titled “Accessors”document
Section titled “document”Get Signature
Section titled “Get Signature”get document():
DocType
Defined in: packages/core/src/peerborne-document.ts:927
Returns
Section titled “Returns”DocType
historyVisibility
Section titled “historyVisibility”Get Signature
Section titled “Get Signature”get historyVisibility():
HistoryVisibility
Defined in: packages/core/src/peerborne-document.ts:1267
Returns
Section titled “Returns”Set Signature
Section titled “Set Signature”set historyVisibility(
value):void
Defined in: packages/core/src/peerborne-document.ts:1263
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.
Parameters
Section titled “Parameters”Returns
Section titled “Returns”void
invitationEpoch
Section titled “invitationEpoch”Get Signature
Section titled “Get Signature”get invitationEpoch():
Uint8Array<ArrayBufferLike> |undefined
Defined in: packages/core/src/peerborne-document.ts:9562
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.
Returns
Section titled “Returns”Uint8Array<ArrayBufferLike> | undefined
latestSnapshot
Section titled “latestSnapshot”Get Signature
Section titled “Get Signature”get latestSnapshot():
CRDTSnapshotNode<ChangesType> |undefined
Defined in: packages/core/src/peerborne-document.ts:7322
Returns the current snapshot, if one exists.
Returns
Section titled “Returns”CRDTSnapshotNode<ChangesType> | undefined
libp2p
Section titled “libp2p”Get Signature
Section titled “Get Signature”get libp2p():
Libp2p
Defined in: packages/core/src/peerborne-document.ts:1435
Returns
Section titled “Returns”Libp2p
pendingWelcomesCount
Section titled “pendingWelcomesCount”Get Signature
Section titled “Get Signature”get pendingWelcomesCount():
number
Defined in: packages/core/src/peerborne-document.ts:9541
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.
Returns
Section titled “Returns”number
pendingWelcomesRetainedBytes
Section titled “pendingWelcomesRetainedBytes”Get Signature
Section titled “Get Signature”get pendingWelcomesRetainedBytes():
number
Defined in: packages/core/src/peerborne-document.ts:9551
Internal
Test/inspection helper: exact number of serialized Welcome bytes retained by the pending-welcomes buffer.
exposed only for unit tests.
Returns
Section titled “Returns”number
Methods
Section titled “Methods”acceptInvitationBootstrap()
Section titled “acceptInvitationBootstrap()”acceptInvitationBootstrap(
bundle,issuerPublicKey,role,founderAddress):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:8482
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.
Parameters
Section titled “Parameters”bundle
Section titled “bundle”issuerPublicKey
Section titled “issuerPublicKey”PublicKey
"reader" | "editor"
founderAddress
Section titled “founderAddress”string
Returns
Section titled “Returns”Promise<void>
addChange()
Section titled “addChange()”addChange(
changeFn):void
Defined in: packages/core/src/peerborne-document.ts:7082
Queue a change function within an active transaction.
Must be called between startChange() and endChange().
Parameters
Section titled “Parameters”changeFn
Section titled “changeFn”ChangeFnType
Returns
Section titled “Returns”void
addReader()
Section titled “addReader()”addReader(
reader,readerKemPublicKey):Promise<BeeKEMWelcomeV2>
Defined in: packages/core/src/peerborne-document.ts:7820
Add a new user as a valid reader. Users are identified by their public keys.
After updating the readers ACL, this attempts to send a BeeKEM Welcome
to the new reader so they receive (a) the keychain changes appropriate
for the document’s historyVisibility setting (so they can decrypt at
least the current state), and (b) the invitation epoch ID they should
record for subsequent since_invited history filtering. The Welcome
is delivered via the beekemWelcomeV2 protocol to every
currently-connected peer; the receiving document ignores Welcomes
addressed to a different reader.
The BeeKEM registration is prepared on a detached tree and the reader ACL is claimed before publication. Live authorization is granted only after publication resolves, in the same synchronous turn that installs the prepared tree and identity caches.
The initial release supports the first reader plus exact retries for that
identity. After removeReader advances the BeeKEM tree, adding a
replacement is rejected before ACL or BeeKEM state changes.
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.
Parameters
Section titled “Parameters”reader
Section titled “reader”PublicKey
User’s identity (signing) public key.
readerKemPublicKey
Section titled “readerKemPublicKey”Uint8Array
Raw SEC1-uncompressed P-256 ECDH public key
(65 bytes) of the reader’s KEM key pair. 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.
Returns
Section titled “Returns”Promise<BeeKEMWelcomeV2>
The BeeKEM Welcome used for this reader.
addWriter()
Section titled “addWriter()”addWriter(
writer):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:7516
Grant write authorization to an existing explicit reader. Users are
identified by their public keys. Call addReader() before promoting a new
writer 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. That binding is recorded in memory when
this document instance adds the reader; readers added before this
instance was opened cannot be promoted. 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.
Parameters
Section titled “Parameters”writer
Section titled “writer”PublicKey
User’s public key
Returns
Section titled “Returns”Promise<void>
assertCanCreateInitialInvitation()
Section titled “assertCanCreateInitialInvitation()”assertCanCreateInitialInvitation():
Promise<void>
Defined in: packages/core/src/peerborne-document.ts:1127
Internal
Validate the deliberately narrow initial membership topology.
Returns
Section titled “Returns”Promise<void>
buildInvitationBootstrap()
Section titled “buildInvitationBootstrap()”buildInvitationBootstrap(
reader,readerKemPublicKey,role,assertCanMutate?):Promise<InvitationBootstrapBundle>
Defined in: packages/core/src/peerborne-document.ts:8077
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.
Parameters
Section titled “Parameters”reader
Section titled “reader”PublicKey
readerKemPublicKey
Section titled “readerKemPublicKey”Uint8Array
"reader" | "editor"
assertCanMutate?
Section titled “assertCanMutate?”() => void
Returns
Section titled “Returns”Promise<InvitationBootstrapBundle>
change()
Section titled “change()”change(
changeFn,message?):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:7286
Applies a new local change (defined by changeFn) to the peerborne document and updates
all peers.
Parameters
Section titled “Parameters”changeFn
Section titled “changeFn”ChangeFnType
A function that makes changes to the current CRDT document.
message?
Section titled “message?”string
An optional change message/description to include.
Returns
Section titled “Returns”Promise<void>
close()
Section titled “close()”close():
Promise<void>
Defined in: packages/core/src/peerborne-document.ts:6525
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.
Returns
Section titled “Returns”Promise<void>
create()
Section titled “create()”create():
Promise<boolean>
Defined in: packages/core/src/peerborne-document.ts:6250
Create a new document under an application-owned path without querying peers.
Returns
Section titled “Returns”Promise<boolean>
createInvitation()
Section titled “createInvitation()”createInvitation(
options):Promise<InvitationOfferV1>
Defined in: packages/core/src/peerborne-document.ts:1119
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.
Parameters
Section titled “Parameters”options
Section titled “options”Returns
Section titled “Returns”Promise<InvitationOfferV1>
endChange()
Section titled “endChange()”endChange(
message?):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:7162
End the transaction and apply all queued changes atomically. This sends a single sync message for all batched changes.
On failure (from any step: write check, CRDT apply, or network publish),
the transaction is aborted and the document reference is rolled back.
For immutable CRDT providers (e.g. Automerge), rollback is reliable
because localChange() returns a new document object.
Known limitation — in-place mutating providers: For CRDT providers
that mutate in place (e.g. Yjs), rollback does NOT undo mutations.
Yjs’s localChange() mutates the document object directly and returns
the same reference, so restoring the saved reference after failure has
no effect — the mutations have already been applied to the shared
Y.Doc. Callers using Yjs should treat a failed transaction as leaving
the local document in a potentially inconsistent state and consider
re-syncing from peers.
Known limitation — concurrent remote changes during rollback: The
rollback sets _document back to the snapshot captured when
endChange() is called (before applying the pending change functions).
Because _makeChange() is async and the node remains
subscribed to pubsub throughout, remote sync messages may arrive and be
applied to _document between the start of the transaction and the
point of failure. Rolling back to the original snapshot reverts those
remote changes as well, not just the local batch. This is acceptable
because the CRDT layer guarantees eventual consistency — the reverted
remote changes will be re-applied on the next sync cycle or document
load. If transaction failure is critical, callers should re-sync the
document after a failed transaction (e.g. call load() or wait for
the next pubsub round) to ensure remote state is promptly restored.
Known limitation — partial internal state on failure: If
_makeChange() fails partway through (e.g. encryption succeeds but
pubsub publish throws), _hashes may retain CIDs for the rolled-back
change (see below). Other counters and bookkeeping fields
(_lastSyncMessage, _documentChangeCount, _changesSinceSnapshot,
_recentTips) ARE restored from snapshots captured before
_makeChange() — see the “Internal metadata rollback” section below
for details.
Specifically, _hashes may retain CIDs for the rolled-back change.
Because _hashes is used to skip already-seen changes during sync,
any CID added before the failure will cause that change to be silently
skipped if it arrives again via pubsub or load(). This means the
rolled-back change is effectively “lost” from this peer’s perspective
until _hashes is rebuilt. Callers should call load() after a
failed transaction to re-sync the full document state from a peer
and restore consistency. A new transaction must be started after a
failure.
Internal metadata rollback: On failure, _lastSyncMessage,
_documentChangeCount, _changesSinceSnapshot, and _recentTips
are restored from snapshots captured before _makeChange().
(_recentTips is bounded to MAX_RECENT_TIPS entries so the snapshot
is a cheap shallow array copy.) For _hashes and
_referencedAncestors, all entries added to each Set after its
pre-attempt size are removed. Because the node remains
subscribed to pubsub during the async transaction, this may include
CIDs appended by concurrent remote syncs, not just local ones.
This is acceptable because CRDT convergence guarantees those remote
CIDs will be re-added on the next sync cycle or document load.
The approach is O(n) iteration but O(delta) memory — no full
array clone — and avoids disrupting any concurrent sync iteration
that clear() would break. A new transaction must be started after
a failure.
Parameters
Section titled “Parameters”message?
Section titled “message?”string
Returns
Section titled “Returns”Promise<void>
Throws
Section titled “Throws”If any step in the commit pipeline fails.
getKemPublicKeyRaw()
Section titled “getKemPublicKeyRaw()”getKemPublicKeyRaw():
Uint8Array<ArrayBufferLike> |undefined
Defined in: packages/core/src/peerborne-document.ts:1110
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 bytes are what inviters pass to
addReader(reader, readerKemPublicKey).
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.
Returns
Section titled “Returns”Uint8Array<ArrayBufferLike> | undefined
getReaders()
Section titled “getReaders()”getReaders():
Promise<PublicKey[]>
Defined in: packages/core/src/peerborne-document.ts:7749
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.
Returns
Section titled “Returns”Promise<PublicKey[]>
List of public keys with read access.
getWriters()
Section titled “getWriters()”getWriters():
Promise<PublicKey[]>
Defined in: packages/core/src/peerborne-document.ts:7490
Get list of writers.
Returns
Section titled “Returns”Promise<PublicKey[]>
List of public keys with write access.
handleBeeKEMPathUpdateRequestData()
Section titled “handleBeeKEMPathUpdateRequestData()”handleBeeKEMPathUpdateRequestData(
payload,admission?):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:10231
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.
Parameters
Section titled “Parameters”payload
Section titled “payload”Uint8Array
admission?
Section titled “admission?”SharedProtocolHandlerAdmission
Returns
Section titled “Returns”Promise<void>
handleBeeKEMWelcomeRequestData()
Section titled “handleBeeKEMWelcomeRequestData()”handleBeeKEMWelcomeRequestData(
payload,admission?):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:9020
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.
Parameters
Section titled “Parameters”payload
Section titled “payload”Uint8Array
The serialized sync message (without the document path header that the shared handler already stripped).
admission?
Section titled “admission?”SharedProtocolHandlerAdmission
Returns
Section titled “Returns”Promise<void>
handleInvitationCatchUpRequestData()
Section titled “handleInvitationCatchUpRequestData()”handleInvitationCatchUpRequestData(
message,stream,admission?):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:3079
Parameters
Section titled “Parameters”message
Section titled “message”stream
Section titled “stream”ProtocolWriteStream
admission?
Section titled “admission?”SharedProtocolHandlerAdmission
Returns
Section titled “Returns”Promise<void>
handleLoadRequestData()
Section titled “handleLoadRequestData()”handleLoadRequestData(
message,stream,admission?):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:3071
Parameters
Section titled “Parameters”message
Section titled “message”stream
Section titled “stream”ProtocolWriteStream
admission?
Section titled “admission?”SharedProtocolHandlerAdmission
Returns
Section titled “Returns”Promise<void>
handleSecurityAdvertiseRequestData()
Section titled “handleSecurityAdvertiseRequestData()”handleSecurityAdvertiseRequestData(
message,stream,admission?):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:4477
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).
Parameters
Section titled “Parameters”message
Section titled “message”The deserialized load request (already parsed by the shared handler).
stream
Section titled “stream”ProtocolWriteStream
The stream object for sending the response.
admission?
Section titled “admission?”SharedProtocolHandlerAdmission
Returns
Section titled “Returns”Promise<void>
handleSnapshotLoadRequestData()
Section titled “handleSnapshotLoadRequestData()”handleSnapshotLoadRequestData(
message,stream,admission?):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:4372
Internal
Handles a snapshot-load request with pre-read stream data. Called by the shared protocol handler in Peerborne after reading and routing.
Parameters
Section titled “Parameters”message
Section titled “message”The deserialized load request (already parsed by the shared handler).
stream
Section titled “stream”ProtocolWriteStream
The stream object for sending the response.
admission?
Section titled “admission?”SharedProtocolHandlerAdmission
Returns
Section titled “Returns”Promise<void>
hasChange()
Section titled “hasChange()”hasChange(
cid):boolean
Defined in: packages/core/src/peerborne-document.ts:7378
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 remains 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).
Parameters
Section titled “Parameters”string
Returns
Section titled “Returns”boolean
historySize()
Section titled “historySize()”historySize():
number
Defined in: packages/core/src/peerborne-document.ts:7314
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.
Returns
Section titled “Returns”number
load()
Section titled “load()”load(
preferredPeer?):Promise<boolean>
Defined in: packages/core/src/peerborne-document.ts:6054
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. The selected response must match the captured challenge and tuple; its derived frontier and complete manifest must match the agreed digest before mutation. 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.
Parameters
Section titled “Parameters”preferredPeer?
Section titled “preferredPeer?”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.
Returns
Section titled “Returns”Promise<boolean>
true after successful loading; false if no usable response is available without a quorum decision. Neither result authorizes creation.
Throws
Section titled “Throws”If required agreement or bound delivery fails.
Throws
Section titled “Throws”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.
Throws
Section titled “Throws”If trust configuration is absent or bootstrap application left incomplete state. Discard an instance with incomplete application.
loadChangeBlock()
Section titled “loadChangeBlock()”loadChangeBlock(
cid):Promise<ChangesType|undefined>
Defined in: packages/core/src/peerborne-document.ts:7351
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.
Returns undefined when:
- The CID is not in
_hashes(we have never seen this change). - 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.
Parameters
Section titled “Parameters”string
CID string of the change block to load.
Returns
Section titled “Returns”Promise<ChangesType | undefined>
The deserialized change payload, or undefined if unavailable.
open()
Section titled “open()”open():
Promise<boolean>
Defined in: packages/core/src/peerborne-document.ts:6240
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.
Returns
Section titled “Returns”Promise<boolean>
true when existing state is activated.
Throws
Section titled “Throws”If state cannot be loaded or another activation is running.
removeReader()
Section titled “removeReader()”removeReader(
reader):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:9608
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.
Parameters
Section titled “Parameters”reader
Section titled “reader”PublicKey
User’s public key.
Returns
Section titled “Returns”Promise<void>
Throws
Section titled “Throws”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.
Throws
Section titled “Throws”If identity/KEM/tree state is missing or divergent, a required commit claim is unavailable, or ACL publication fails.
Throws
Section titled “Throws”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()
Section titled “removeWriter()”removeWriter(
writer,options?):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:7646
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.
Parameters
Section titled “Parameters”writer
Section titled “writer”PublicKey
User’s public key
options?
Section titled “options?”Set requireRemainingWriter to reject removal of the last
writer with LastWriterRemovalError.
Returns
Section titled “Returns”Promise<void>
setKemKeyPair()
Section titled “setKemKeyPair()”setKemKeyPair(
keyPair):Promise<void>
Defined in: packages/core/src/peerborne-document.ts:1067
Install the recipient-side ECDH (P-256) key pair used to open
incoming BeeKEM Welcome sealed payloads. The application is
responsible for persisting and re-supplying this key pair across
sessions; the matching raw public key (see
getKemPublicKeyRaw) must be communicated out-of-band to any
writer who will invite this user, so they can pass it to
addReader(reader, readerKemPublicKey).
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.
Parameters
Section titled “Parameters”keyPair
Section titled “keyPair”CryptoKeyPair | undefined
Returns
Section titled “Returns”Promise<void>
snapshot()
Section titled “snapshot()”snapshot():
Promise<CRDTSnapshotNode<ChangesType> |undefined>
Defined in: packages/core/src/peerborne-document.ts:7393
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.
Returns
Section titled “Returns”Promise<CRDTSnapshotNode<ChangesType> | undefined>
The created snapshot node, or undefined if the provider does not support snapshots.
Throws
Section titled “Throws”If the current user does not have write access to this document. Only writers are authorized to create snapshots.
startChange()
Section titled “startChange()”startChange():
void
Defined in: packages/core/src/peerborne-document.ts:7069
Start a change transaction. Changes made via addChange() will be batched
and applied atomically when endChange() is called.
Returns
Section titled “Returns”void
subscribe()
Section titled “subscribe()”subscribe(
id,handler,originFilter?):void
Defined in: packages/core/src/peerborne-document.ts:7025
Subscribes a change handler to the document. Use this method to receive real-time updates to the document.
Parameters
Section titled “Parameters”string
A unique id for this handler. Used to unsubscribe this handler.
handler
Section titled “handler”PeerborneDocumentChangeHandler<DocType, PublicKey>
A function that is called when a change is received.
originFilter?
Section titled “originFilter?”"all" | "remote" | "local"
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.
Returns
Section titled “Returns”void
sync()
Section titled “sync()”sync(
message):Promise<boolean>
Defined in: packages/core/src/peerborne-document.ts:6574
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.
Parameters
Section titled “Parameters”message
Section titled “message”OrdinarySyncMessage<ChangesType>
A sync message to apply.
Returns
Section titled “Returns”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()
Section titled “unsubscribe()”unsubscribe(
id):void
Defined in: packages/core/src/peerborne-document.ts:7053
Unsubscribes a change handler from the document.
Parameters
Section titled “Parameters”string
The id of the handler to unsubscribe.
Returns
Section titled “Returns”void