Skip to main content

@idpass/data-collect-core / EventStoreImpl

Class: EventStoreImpl

Defined in: components/EventStore.ts:147

Event store implementation providing tamper-evident event sourcing with Merkle tree integrity.

The EventStoreImpl is the core component for managing immutable event storage with cryptographic integrity verification. It implements complete event sourcing capabilities including audit trails, Merkle tree verification, and sync timestamp management.

Key features:

  • Immutable Event Storage: All events are stored as immutable records.
  • Merkle Tree Integrity: Cryptographic verification of event integrity using SHA256.
  • Audit Trail Management: Complete audit logging for compliance and debugging.
  • Sync Coordination: Timestamp tracking for multiple sync operations.
  • Event Verification: Merkle proof generation and verification.
  • Pagination Support: Efficient handling of large event datasets.
  • Tamper Detection: Cryptographic detection of unauthorized modifications.

Architecture:

  • Uses pluggable storage adapters for different persistence backends.
  • Maintains in-memory Merkle tree for fast integrity verification.
  • Implements event sourcing patterns with append-only semantics.
  • Provides both sync and async operations for different use cases.
  • Supports multiple sync levels (LOCAL, REMOTE, EXTERNAL).

Examples

Basic usage:

const eventStore = new EventStoreImpl(
storageAdapter
);

await eventStore.initialize();

// Save an event
const eventId = await eventStore.saveEvent({
guid: 'event-456',
entityGuid: 'person-789',
type: 'create-individual',
data: { name: 'John Doe', age: 30 },
timestamp: new Date().toISOString(),
userId: 'user-123',
syncLevel: SyncLevel.LOCAL
});

// Verify integrity
const merkleRoot = eventStore.getMerkleRoot();
console.log('Current Merkle root:', merkleRoot);

Event verification with Merkle proofs:

// Get proof for an event
const proof = await eventStore.getProof(event);

// Verify event integrity
const isValid = eventStore.verifyEvent(event, proof);
if (isValid) {
console.log('Event integrity verified');
} else {
console.error('Event has been tampered with!');
}

Audit trail management:

// Log audit entry
await eventStore.logAuditEntry({
guid: 'audit-123',
timestamp: new Date().toISOString(),
userId: 'user-456',
action: 'create-individual',
eventGuid: 'event-789',
entityGuid: 'person-101',
changes: { name: 'John Doe' },
signature: 'sha256:...'
});

// Get audit trail for entity
const auditTrail = await eventStore.getAuditTrailByEntityGuid('person-101');
auditTrail.forEach(entry => {
console.log(`${entry.timestamp}: ${entry.action} by ${entry.userId}`);
});

Sync operations:

// Check for events since last sync
const lastSync = await eventStore.getLastRemoteSyncTimestamp();
const newEvents = await eventStore.getEventsSince(lastSync);

if (newEvents.length > 0) {
console.log(`${newEvents.length} events to sync`);

// Process sync...

// Update sync timestamp
await eventStore.setLastRemoteSyncTimestamp(new Date().toISOString());
}

Implements

Constructors

Constructor

new EventStoreImpl(storageAdapter): EventStoreImpl

Defined in: components/EventStore.ts:168

Creates a new EventStoreImpl instance.

Parameters

storageAdapter

EventStorageAdapter

Storage adapter for persistence (IndexedDB, PostgreSQL, etc.).

Returns

EventStoreImpl

Example

// With IndexedDB for browser
const indexedDbAdapter = new IndexedDbEventStorageAdapter('tenant-123');
const browserEventStore = new EventStoreImpl(indexedDbAdapter);

// With PostgreSQL for server
const postgresAdapter = new PostgresEventStorageAdapter(connectionString, 'tenant-123');
const serverEventStore = new EventStoreImpl(postgresAdapter);

Methods

updateSyncLevelFromEvents()

updateSyncLevelFromEvents(events): Promise<void>

Defined in: components/EventStore.ts:178

Updates sync levels for multiple events.

Parameters

events

FormSubmission[]

Array of form submissions to update.

Returns

Promise<void>

A Promise that resolves when sync levels are updated.

Implementation of

EventStore.updateSyncLevelFromEvents


closeConnection()

closeConnection(): Promise<void>

Defined in: components/EventStore.ts:187

Closes database connections and cleans up resources.

Returns

Promise<void>

A Promise that resolves when the connection is closed.

Implementation of

EventStore.closeConnection


initialize()

initialize(): Promise<void>

Defined in: components/EventStore.ts:209

Initializes the event store and loads the Merkle tree for integrity verification.

Returns

Promise<void>

A Promise that resolves when the store is initialized.

Throws

When storage initialization fails.

Example

const eventStore = new EventStoreImpl(storageAdapter);

try {
await eventStore.initialize();
console.log('Event store ready');
} catch (error) {
console.error('Failed to initialize event store:', error);
}

Implementation of

EventStore.initialize


saveEvent()

saveEvent(form): Promise<string>

Defined in: components/EventStore.ts:275

Saves an event and updates the Merkle tree for integrity verification.

Parameters

form

FormSubmission

Form submission/event to save.

Returns

Promise<string>

Unique identifier for the saved event.

Throws

When event storage fails.

Example

const eventId = await eventStore.saveEvent({
guid: 'event-123',
entityGuid: 'person-456',
type: 'create-individual',
data: { name: 'John Doe', age: 30 },
timestamp: new Date().toISOString(),
userId: 'user-789',
syncLevel: SyncLevel.LOCAL
});

console.log('Event saved with ID:', eventId);

Implementation of

EventStore.saveEvent


getEvents()

getEvents(): Promise<FormSubmission[]>

Defined in: components/EventStore.ts:287

Retrieves all events from the event store.

Returns

Promise<FormSubmission[]>

Array of all form submissions/events.

Implementation of

EventStore.getEvents


getAllEvents()

getAllEvents(): Promise<FormSubmission[]>

Defined in: components/EventStore.ts:296

Retrieves all events in the store.

Returns

Promise<FormSubmission[]>

Array of all form submissions/events.

Implementation of

EventStore.getAllEvents


isEventExisted()

isEventExisted(guid): Promise<boolean>

Defined in: components/EventStore.ts:306

Checks if an event with the given GUID exists.

Parameters

guid

string

The GUID of the event to check.

Returns

Promise<boolean>

true if the event exists, false otherwise.

Implementation of

EventStore.isEventExisted


getMerkleRoot()

getMerkleRoot(): string

Defined in: components/EventStore.ts:333

Gets the current Merkle tree root hash for integrity verification.

The root hash represents the cryptographic fingerprint of all events in the store. Any modification to any event will change this hash.

Returns

string

SHA256 hash of the Merkle tree root, or empty string if no events.

Example

const rootHash = eventStore.getMerkleRoot();
console.log('Current integrity hash:', rootHash);

// Store this hash for later verification
const storedHash = rootHash;

// Later, after potential tampering...
const currentHash = eventStore.getMerkleRoot();
if (currentHash !== storedHash) {
console.error('Data integrity compromised!');
}

Implementation of

EventStore.getMerkleRoot


verifyEvent()

verifyEvent(event, proof): boolean

Defined in: components/EventStore.ts:363

Verifies an event's integrity using a Merkle proof.

This method cryptographically verifies that an event has not been tampered with by checking its Merkle proof against the current root hash.

Parameters

event

FormSubmission

Event to verify.

proof

string[]

Merkle proof path (array of sibling hashes).

Returns

boolean

true if event is authentic and untampered, false otherwise.

Example

// Get proof for an event
const proof = await eventStore.getProof(suspiciousEvent);

// Verify the event
const isValid = eventStore.verifyEvent(suspiciousEvent, proof);

if (isValid) {
console.log('Event integrity verified - data is authentic');
} else {
console.error('Event verification failed - possible tampering detected!');
// Take appropriate security measures
}

Implementation of

EventStore.verifyEvent


getProof()

getProof(event): Promise<string[]>

Defined in: components/EventStore.ts:384

Retrieves the Merkle tree proof for a specific event.

Parameters

event

FormSubmission

The event to get the proof for.

Returns

Promise<string[]>

An array of sibling hashes forming the Merkle proof.

Implementation of

EventStore.getProof


logAuditEntry()

logAuditEntry(entry): Promise<void>

Defined in: components/EventStore.ts:416

Logs a single audit entry.

Parameters

entry

AuditLogEntry

The audit log entry to save.

Returns

Promise<void>

A Promise that resolves when the entry is logged.

Implementation of

EventStore.logAuditEntry


saveAuditLogs()

saveAuditLogs(entries): Promise<void>

Defined in: components/EventStore.ts:426

Saves multiple audit log entries.

Parameters

entries

AuditLogEntry[]

An array of audit log entries to save.

Returns

Promise<void>

A Promise that resolves when entries are saved.

Implementation of

EventStore.saveAuditLogs


clearStore()

clearStore(): Promise<void>

Defined in: components/EventStore.ts:443

Clears all data from the store (for testing).

Returns

Promise<void>

A Promise that resolves when the store is cleared.

Implementation of

EventStore.clearStore


updateEventSyncLevel()

updateEventSyncLevel(id, syncLevel): Promise<void>

Defined in: components/EventStore.ts:456

Updates the sync level of an event.

Parameters

id

string

The ID of the event to update.

syncLevel

SyncLevel

The new sync level.

Returns

Promise<void>

A Promise that resolves when the sync level is updated.

Implementation of

EventStore.updateEventSyncLevel


updateAuditLogSyncLevel()

updateAuditLogSyncLevel(entityId, syncLevel): Promise<void>

Defined in: components/EventStore.ts:467

Updates the sync level of an audit log entry.

Parameters

entityId

string

The ID of the entity associated with the audit log.

syncLevel

SyncLevel

The new sync level.

Returns

Promise<void>

A Promise that resolves when the sync level is updated.

Implementation of

EventStore.updateAuditLogSyncLevel


getEventsSince()

getEventsSince(timestamp): Promise<FormSubmission[]>

Defined in: components/EventStore.ts:477

Retrieves events created since a specific timestamp.

Parameters

timestamp

The timestamp to filter events from.

string | Date

Returns

Promise<FormSubmission[]>

An array of events created after the specified timestamp.

Implementation of

EventStore.getEventsSince


getEventsSincePagination()

getEventsSincePagination(timestamp, limit): Promise<{ events: FormSubmission[]; nextCursor: string | Date | null; }>

Defined in: components/EventStore.ts:488

Retrieves events since a timestamp with pagination support.

Parameters

timestamp

The timestamp to filter events from.

string | Date

limit

number

The maximum number of events to return (default: 10).

Returns

Promise<{ events: FormSubmission[]; nextCursor: string | Date | null; }>

An object with an events array and a nextCursor for the next page.

Implementation of

EventStore.getEventsSincePagination


getAuditLogsSince()

getAuditLogsSince(timestamp): Promise<AuditLogEntry[]>

Defined in: components/EventStore.ts:501

Retrieves audit logs created since a specific timestamp.

Parameters

timestamp

string

The timestamp to filter audit logs from.

Returns

Promise<AuditLogEntry[]>

An array of audit log entries created after the specified timestamp.

Implementation of

EventStore.getAuditLogsSince


getLastRemoteSyncTimestamp()

getLastRemoteSyncTimestamp(): Promise<string>

Defined in: components/EventStore.ts:510

Retrieves the timestamp of the last remote synchronization.

Returns

Promise<string>

A Promise that resolves with the timestamp string.

Implementation of

EventStore.getLastRemoteSyncTimestamp


setLastRemoteSyncTimestamp()

setLastRemoteSyncTimestamp(timestamp): Promise<void>

Defined in: components/EventStore.ts:520

Sets the timestamp of the last remote synchronization.

Parameters

timestamp

string

The timestamp string to set.

Returns

Promise<void>

A Promise that resolves when the timestamp is set.

Implementation of

EventStore.setLastRemoteSyncTimestamp


getLastLocalSyncTimestamp()

getLastLocalSyncTimestamp(): Promise<string>

Defined in: components/EventStore.ts:529

Retrieves the timestamp of the last local synchronization.

Returns

Promise<string>

A Promise that resolves with the timestamp string.

Implementation of

EventStore.getLastLocalSyncTimestamp


setLastLocalSyncTimestamp()

setLastLocalSyncTimestamp(timestamp): Promise<void>

Defined in: components/EventStore.ts:539

Sets the timestamp of the last local synchronization.

Parameters

timestamp

string

The timestamp string to set.

Returns

Promise<void>

A Promise that resolves when the timestamp is set.

Implementation of

EventStore.setLastLocalSyncTimestamp


getLastPullExternalSyncTimestamp()

getLastPullExternalSyncTimestamp(): Promise<string>

Defined in: components/EventStore.ts:548

Retrieves the timestamp of the last external sync pull operation.

Returns

Promise<string>

A Promise that resolves with the timestamp string.

Implementation of

EventStore.getLastPullExternalSyncTimestamp


setLastPullExternalSyncTimestamp()

setLastPullExternalSyncTimestamp(timestamp): Promise<void>

Defined in: components/EventStore.ts:558

Sets the timestamp of the last external sync pull operation.

Parameters

timestamp

string

The timestamp string to set.

Returns

Promise<void>

A Promise that resolves when the timestamp is set.

Implementation of

EventStore.setLastPullExternalSyncTimestamp


getLastPushExternalSyncTimestamp()

getLastPushExternalSyncTimestamp(): Promise<string>

Defined in: components/EventStore.ts:567

Retrieves the timestamp of the last external sync push operation.

Returns

Promise<string>

A Promise that resolves with the timestamp string.

Implementation of

EventStore.getLastPushExternalSyncTimestamp


setLastPushExternalSyncTimestamp()

setLastPushExternalSyncTimestamp(timestamp): Promise<void>

Defined in: components/EventStore.ts:577

Sets the timestamp of the last external sync push operation.

Parameters

timestamp

string

The timestamp string to set.

Returns

Promise<void>

A Promise that resolves when the timestamp is set.

Implementation of

EventStore.setLastPushExternalSyncTimestamp


getAuditTrailByEntityGuid()

getAuditTrailByEntityGuid(entityGuid): Promise<AuditLogEntry[]>

Defined in: components/EventStore.ts:587

Retrieves the complete audit trail for a specific entity.

Parameters

entityGuid

string

The global unique identifier of the entity.

Returns

Promise<AuditLogEntry[]>

An array of audit log entries in chronological order.

Implementation of

EventStore.getAuditTrailByEntityGuid