@burdenoff/be-sdk
v2026.1121.1
Published
Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more
Maintainers
Readme
@burdenoff/be-sdk
Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more.
Published automatically using npm trusted publishers (OIDC) - no long-lived tokens needed!
Installation
npm install @burdenoff/be-sdkQuick Start
import { BurdenoffSDK } from '@burdenoff/be-sdk';
// Initialize SDK
const sdk = new BurdenoffSDK({
workspacesApiUrl: 'https://api.burdenoff.com/graphql',
tenantApiUrl: 'https://tenant.burdenoff.com/graphql',
context: {
userId: 'user-123',
workspaceId: 'workspace-456',
token: 'your-jwt-token',
},
});
// Send notification
await sdk.notifications.send({
title: 'Welcome',
message: 'Hello from Burdenoff!',
userIds: ['user-123'],
type: 'info',
});
// Track operation with RBAC + Activity + Usage
await sdk.tracker.trackOperation({
operationName: 'createProject',
userId: 'user-123',
rbacCheck: { workspaceId: 'workspace-456' },
activityOptions: {
description: 'Created new project',
metadata: { projectName: 'My Project' },
},
usageOptions: {
billingAccountId: 'billing-123',
},
});
// Check permissions
await sdk.rbac.requirePermission({
userId: 'user-123',
action: 'create:project',
resourceType: 'project',
workspaceId: 'workspace-456',
});
// Record activity
await sdk.activity.record({
userId: 'user-123',
action: 'PROJECT_CREATED',
description: 'Created new project',
productId: 'WORKSPACE',
workspaceId: 'workspace-456',
});
// Add usage
await sdk.usage.add({
billingAccountId: 'billing-123',
quotaName: 'api_calls',
value: 1,
description: 'API call for project creation',
});
// Export product translations from i18n service
const hiDictionary = await sdk.translation.exportProductTranslations({
productName: 'vibecontrols',
languageCode: 'hi',
format: 'JSON',
decodeJson: true,
});
// Upsert product translations (creates missing keys/translations, publishes)
await sdk.translation.upsertProductTranslations({
productName: 'vibecontrols',
languageCode: 'ta',
translations: {
'overviewPage.title': 'VibeControls மேலோட்டம்',
},
});Tenant notification delivery
Workspace services use the private GLOBAL_PUBLIC_GATEWAY_URL for tenant/global calls.
Supply the actual service identity through the normal runtime configuration. Per-request
workspace and organization context can be passed without mutating a shared SDK instance:
import {
TenantNotificationChannel,
TenantNotificationType,
} from '@burdenoff/be-sdk';
const notificationId = await sdk.tenantNotifications.send(
{
recipient: { userId: recipientId },
channel: TenantNotificationChannel.IN_APP,
type: TenantNotificationType.SYSTEM,
subject: 'Workflow completed',
body: 'Your workflow has completed.',
metadata: { eventId, resourceId },
expiresAt,
},
{ workspaceId, organizationId },
);send() uses the owner's trigger API, preserving metadata and expiry, and returns a real
notification identifier only after acknowledgement. External delivery remains asynchronous.
A supplied scheduledFor uses the dedicated scheduling API. Batch notifications must share
a schedule; use individual sends for different schedules. The legacy batch totalQueued
field aliases the owner's totalTriggered acceptance counter, not a final delivery count.
Read/delete helpers return the owner's acknowledgement, including false for incomplete
operations. List helpers unwrap owner connections; template inventory is paginated completely
within a bounded limit. getStats() exposes actual owner counters, including triggered,
scheduled and cancelled; deprecated queued and processing fields are absent because the
owner does not publish those measurements. The TenantNotificationType delivery-intent enum
is distinct from the convenience API's severity enum.
Features
- Unified Tracking: Single function for RBAC + Activity + Usage + Quota checking
- Notifications: Send in-app, email, SMS, and push notifications
- RBAC: Role-based access control and permission management
- Activity Logging: Comprehensive audit trail for all operations
- Usage Tracking: Track resource consumption for billing
- Graph Integration: Global search across all products
- Context Management: Automatic context propagation
- Event Queue: NATS integration for event-driven architecture
- Database Helpers: Prisma utilities and transaction management
- Authentication: JWT verification and token management
- Payments: Payment processing and webhook handling
- Translation: Backend i18n support
- Search: Advanced search utilities
- Logger: Structured logging compatible with console
Modules
Core Modules
- tracker: Unified operation tracking (RBAC + Activity + Usage + Notifications)
- logger: Structured logging system
- context: Request context management
- client: GraphQL client with retry logic
Integration Modules
- notifications: Notification management
- rbac: Permission and access control
- activity: Activity logging
- usage: Usage and quota tracking
- graph: Knowledge graph integration
- events: Event queue (NATS) integration
- auth: Authentication and JWT handling
Utility Modules
- database: Prisma helpers
- search: Search utilities
- translation: i18n support
- payments: Payment processing
- bootstrap: Server initialization
- platform: Scale primitives (see below)
- validation: User-field validators and the
@rbaccoverage guard (see below) - tags: Shared entity tagging over wspace-tags-svc (see below)
- files: Shared client for workspace blobs owned by wspace-files-svc (see below)
RBAC coverage guard (@burdenoff/be-sdk/validation)
assertRbacCoverage(pathOrDocuments, options) parses a svc's SDL (a directory of
.gql/.graphql files, or a single file such as .hive-schema.graphql) and fails when a
Query/Mutation/Subscription field has no @rbac, has one the gateway would deny as invalid
(missing action/resource/scopeType, unknown scopeType, entity without scopeArg),
or has a resourceIdArg/scopeArg that does not resolve to one ID/String within two
segments. Pass selfScopedFields to pin the reviewed scopeType: "self" surface. Call it
from one unit test per svc:
import { join } from 'node:path';
import { assertRbacCoverage } from '@burdenoff/be-sdk/validation';
it('gates every root field with a well-formed @rbac', () => {
assertRbacCoverage(join(__dirname, '../modules'), {
minRootFields: 200, // a wrong path must not pass
selfScopedFields: { mySettings: 'type C: resolver filters by ctx.actorId' },
});
});analyzeRbacCoverage returns the same report without throwing.
Entity tags (@burdenoff/be-sdk/tags)
One implementation of "let users tag my entities" for every svc, replacing the per-svc
EntityTagAdapter copies. Everything goes to wspace-tags-svc through the internal
workspace gateway with the caller's x-actor-* / x-workspace-id forwarded.
TagsGatewayAdaptertakes the svc's entity types, its default vocabulary and default source, and provides get / tag / untag / replace, search / list / create tags (inline create resolves or creates the default vocabulary), andfindEntityIdsByTagsfor server-side filter-by-tag. Inputs are validated (EntityTagsErrorwith a stablecode).buildEntityTagsSdl({ prefix, rbac, extendTypes })emits the whole surface under a per-svc prefix, because two subgraphs declaring the same non-shareable tag types break composition. Every root field carries a static@rbac.typeNames/externalTypeskeep already-published names (VibeControls shipsEntityTagAssignment,AvailableTag).createEntityTagResolvers({ prefix, adapter, entities })returns the matchingQuery/Mutation/ per-typetagAssignmentsresolvers (fail-soft reads), withauthorizeEntity(ownership check: throw NOT_FOUND),onMutation(audit) andmapError(svc i18n errors) hooks.
import { TagsGatewayAdapter, buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';
const adapter = new TagsGatewayAdapter({
serviceName: 'wspace-workflow-svc',
entityTypes: ['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN', 'FLUIDGRIDS_DATATABLE'],
vocabulary: { key: 'fluidgrids-tags', name: 'FluidGrids Tags' },
});
export const typeDefs = buildEntityTagsSdl({
prefix: 'Fluidgrids', // fluidgridsEntityTags, tagFluidgridsEntity, FluidgridsTagAssignment, ...
productLabel: 'FluidGrids',
rbac: { resource: 'workflow' },
extendTypes: ['WorkflowDefinition', 'WorkflowRun', 'DataTable'],
includeEntitiesByTags: true,
});
export const { Query, Mutation, types } = createEntityTagResolvers({
prefix: 'Fluidgrids',
adapter,
includeEntitiesByTags: true,
entities: {
// Versioned rows: tag the logical key so every version shares one tag set.
WorkflowDefinition: { entityType: 'FLUIDGRIDS_WORKFLOW', entityId: (p) => String(p.workflowKey ?? '') },
WorkflowRun: { entityType: 'FLUIDGRIDS_RUN' },
DataTable: { entityType: 'FLUIDGRIDS_DATATABLE' },
},
});Files client (@burdenoff/be-sdk/files)
wspace-files-svc owns every workspace blob. Services must not presign object storage
themselves or hold storage credentials: hand the bytes to FilesClient and persist only
the opaque fileId. Every call goes through the internal workspace gateway with the
CALLER's x-actor-* / x-workspace-id, so the File row is owned by the user who asked
for it and files-svc applies quota, folder access and read permission to that user. The
service must still authorize the action itself (its own @rbac plus a scoped row lookup).
uploadFileruns the files-svc protocol:initiateUpload→ presigned PUT (DIRECT) or per-part PUTs +registerUploadedPart(MULTIPART, which files-svc picks above 5 MiB) →completeUploadwith the samefileSizestring (required). The SHA-256 is declared at both ends; a failed upload aborts its session.requireFileproves a caller-suppliedfileIdis an ACTIVE, actor-readable File in the actor's workspace (throwsNOT_FOUND, never a permission error) before you store it.getDownloadUrlmints a short-lived URL on demand (clamped to 60 s – 7 days, the S3 presign cap); never persist it.downloadFile/downloadFileAsBase64fetch the bytes for server-side processing with a size cap.deleteFiletrashes (orpermanent).FileReference(toFileReference,isFileReference) is the JSON-safe pointer that node outputs, attachments and evidence rows carry instead of inline base64.- Only scalar
Filefields are read through the ROOTgetFilefield: files-svc'sFileentity has no__resolveReference, so never select federatedfile { name }elsewhere. - Errors are
FilesClientErrorwith a stablecode(NOT_FOUND,QUOTA_EXCEEDED,TOO_LARGE,STORAGE_ERROR, …) andgraphqlCode.
import { FilesClient, toFileReference } from '@burdenoff/be-sdk/files';
const files = new FilesClient({ serviceName: 'wspace-vibecontrols-svc' });
const actor = { actorId: ctx.actorId, workspaceId: ctx.workspaceId };
const stored = await files.uploadFile(
{ fileName: 'access-review.pdf', data: pdfBytes, mimeType: 'application/pdf', description: 'SOC 2 evidence' },
actor
);
await db.securityEvidence.update({ where: { id }, data: { fileId: stored.fileId } });
const url = await files.getDownloadUrl(evidence.fileId, actor, { expiresInSeconds: 300 });
const output = { attachment: toFileReference(stored) }; // workflow node output, no base64AI-credit meter (@burdenoff/be-sdk/ai-credits)
Cost-weighted, idempotent charging of a completed assistant turn, shared by every product
that meters its assistant (replaces the VibeControls usage-billing.ts and HealthyBowl
ai-credit-usage.ts copies).
chargevalidates the report (session, message, model, integer non-negative token counts, ≤ 2,000,000 per report), prices it server-side with global-billingquoteAiCredits(cross-layerGatewayClient,GLOBAL_PUBLIC_GATEWAY_URL) and records it with wspace-activitytrackUsageon<productId>.ai.creditsthrough the wspace internal gateway (WSPACE_INT_GATEWAY_URL,x-workspace-id).- Idempotent: the usage record's hash is
<prefix>:<sessionId>:<messageId>(components%/:-escaped), and activity's uniqueusage_records.hashmakes a replay a no-op. The default prefix is<productId>:aicredit; a product that already records under another prefix must keep it (aicreditfor VibeControls,hb-assistantfor HealthyBowl), or a retry across the deploy is charged twice. - Only a malformed report throws (
AiCreditInputError, map toBAD_USER_INPUT). Pricing or recording failures never fail the user's turn: they return{ status: 'skipped', reason: 'NOT_PRICED' | 'ZERO_COST' | 'GUARD_REFUSED' | 'RECORD_FAILED' }and are logged. A null quote never charges an invented amount. guardis an optional pre-charge hook (e.g. a per-workspace report-rate ceiling); a guard that throws fails open.readUsage(workspaceId)returns the enforced counter (all active assignment rows summed, ascheckWorkspaceQuotasums them), or null when unreachable / not provisioned.- The charging GraphQL field takes the workspace from the gateway context, carries
@rbac, and must NOT carry@usage(trackUsage: true)— that would charge a second, flat amount. A pre-flight gate is a separate@usage(checkQuota: true, trackUsage: false)field.
import { AiCreditMeter, isAiCreditInputError } from '@burdenoff/be-sdk/ai-credits';
const meter = new AiCreditMeter({ productId: 'vibecontrols', serviceName: 'wspace-vibecontrols-svc', hashPrefix: 'aicredit' });
const result = await meter.charge({
workspaceId: requireWorkspaceId(ctx.workspace?.id), // gateway context, never the payload
userId: ctx.actor?.id,
sessionId: input.sessionId,
messageId: input.messageId,
model: input.model,
inputTokens: input.inputTokens,
outputTokens: input.outputTokens,
});
if (result.status === 'skipped') logAudit(/* … */);Platform Primitives (@burdenoff/be-sdk/platform)
Reusable building blocks consumed fleet-wide as part of the scale refactor:
| Primitive | Purpose |
|-----------|---------|
| httpClient / createHttpClient | Hardened fetch wrapper: per-request AbortSignal.timeout (default 5s), retries with jitter, per-host circuit breaker (opens at 5 consecutive 5xx, half-open after 30s). |
| withLeaderLock(redis, name, fn, { ttlMs, renewMs }) | Redis-based leader election via SET NX EX; auto-renews while fn() runs; releases via token-checked LUA DEL. |
| rateLimitIncr(redis, { key, limit, windowMs }) | Atomic INCR + EXPIRE NX rate limiter. Returns { allowed, remaining, resetAt }. |
| buildLoaders + resolveReferenceLoader | Per-request DataLoader factory + Apollo Federation __resolveReference helper. |
| clampLimit + paginate | Cursor pagination (take = limit + 1 to compute hasMore and nextCursor). |
| LLMRouter | Multi-provider LLM wrapper (Anthropic / OpenAI / OpenRouter) with timeout, retries with jitter, provider fallback chain (env LLM_PROVIDER_CHAIN), and token cap. |
| ensureMonthlyPartitions / dropOldPartitions | PostgreSQL monthly RANGE partition creation + retention drop. |
| buildCacheKey / invalidateNamespace | Versioned-key cache invalidation (INCR v:{namespace} — no KEYS/SCAN). |
import { Platform } from '@burdenoff/be-sdk';
// or: import { httpClient, withLeaderLock, ... } from '@burdenoff/be-sdk/platform';
const response = await Platform.httpClient('https://api.example.com/v1/users');
await Platform.withLeaderLock(redis, 'nightly-cleanup', async () => {
// only one replica runs this
}, { ttlMs: 60_000 });
const { allowed } = await Platform.rateLimitIncr(redis, {
key: `signup:${ip}`,
limit: 5,
windowMs: 60_000,
});Documentation
For detailed documentation, see:
- API Reference
- Integration Guide
- Examples
- Migration Guide
- Internal Client Architecture - Service-to-service communication and header transformation
Development
# Install dependencies
npm install
# Run tests
npm test
# Build
npm run build
# Lint
npm run lint
# Format
npm run formatLicense
PROPRIETARY - Copyright Burdenoff Consultancy Services Pvt. Ltd.
Support
For support, email [email protected] or visit https://burdenoff.com/support.
Shared DuckLake dataset contract (BOFF-8254)
The DuckLake catalog PostgreSQL database owns shared_lake_datasets and
shared_lake_dataset_consumers (migration in prisma/lake-registry/).
dataset_id is the existing BigConsole sink UUID, metadata_schema is
dl_<UUID with underscores>, and the S3 prefix stays
datasinks/<dataset_id>/. BigConsole's service database continues to own the
ingest watermark and dashboard payload behavior; it mirrors legacy metadata
to this registry. Run its idempotent scripts/backfill-shared-lake-registry.ts
after the catalog migration, then let normal writes keep it current.
Legacy payload_versions and payload_elements are JSON dashboard data, not
an operational TimeCampus contract. A product owner adds a typed table in the
same catalog schema (or a new dataset), with non-null workspace_id and
nullable product_id. A null product_id explicitly marks a row shared with
all approved dataset consumers. Product-specific rows carry their product
slug. Readers use both workspace_id and (product_id = consumer OR
product_id IS NULL) in every query. Column names and types are versioned by
schema_version; an incompatible change requires a new version/table and a
staged consumer migration. A single designated owner writes each typed table;
readers never write. Owners serialize commits and update
last_committed_version only after the lake transaction succeeds. Add DuckLake
product/date partitions only after file-size and query-profile evidence shows
that pruning is useful; partitions are a performance choice, not an access
control mechanism.
The first TimeCampus GraphQL operation exposes only typed time_entries
tables classified L1 or L2. Other approved datasets remain service-only until
their fields and end-user RBAC are reviewed explicitly.
Rollout for a TimeCampus grant:
- Apply
bun run lake:registry:migrateagainst the catalog withDUCKLAKE_REGISTRY_MIGRATION_URL. Backfill existing BigConsole sinks. - Create the typed table and a representative fixture in alpha, validate
workspace/product columns and version, then call
registerTypedwith the original sink ID/routing andlifecycle: 'ready'. BigConsole continues using its legacy payload tables in the same schema. - Add the dataset UUID to
timecampus_ducklake_dataset_ids.alphaintf-aws-cloud/roots/secrets, review/apply the S3 policy through IaC, and provision a separate static access key in the TimeCampus Secrets Manager bundle. The TimeCampus catalog login must be a member of theboff_timecampus_lake_readerrole; put its read-only URL inDUCKLAKE_CATALOG_URL. AddDUCKLAKE_S3_BUCKET,DUCKLAKE_S3_ACCESS_KEY_ID, andDUCKLAKE_S3_SECRET_ACCESS_KEYto the same bundle. The workload already imports its bundle through GitOps. - Run
bun run lake:grant:timecampuswith the approvedLAKE_DATASET_IDandLAKE_GRANT_ACTOR. This grants catalog schema SELECT and activates the product grant. The approved view prevents TimeCampus's catalog login from reading the unfiltered registry tables. The IAM key can read only the reviewed S3 prefix. Validate discovery, direct read, denied guessed ID, and mixed-product rows withtimecampus-doctor/wspace/modules/timecampus/scripts/test-timecampus.sh --test lakein alpha; then repeat the reviewed grant and validation in prod.
To adopt a second product, add its own catalog view and NOLOGIN reader role,
per-dataset PostgreSQL schema grants, IAM principal/prefix policy, Secrets
Manager bundle values, and service using LakeDatasetRegistry plus
AuthorizedLakeReader. Grant revocation must use
LAKE_GRANT_ACTION=revoke bun run lake:grant:timecampus, remove the dataset
UUID from the Terraform S3 policy, and rotate credentials if a removed product
previously held them. Do not share BigConsole's broad lake credentials.
