Open Enterprise
Browse topics
DocumentationApplication integration

@open-enterprise/sdk

TypeScript client for the Open Enterprise runtime. It runs on Node.js 22 or later and on edge runtimes that provide fetch and Web Crypto. Keep the client and its credentials on your backend.

Shell
npm install @open-enterprise/sdk

Entry points

Import Contents
@open-enterprise/sdk EnterpriseClient, EnterpriseError, EventPoller, and the API types
@open-enterprise/sdk/webhooks verifyWebhook, createWebhookSignature, WebhookVerificationError
@open-enterprise/sdk/sync VendorSync and SYNC_SCHEMA_SQL, for a copy in your database

No entry point imports a node: module. Webhook verification uses crypto.subtle, so its functions return promises.

Use the client

TypeScript
import { EnterpriseClient } from "@open-enterprise/sdk";

const enterprise = new EnterpriseClient({
  endpoint: process.env.ENTERPRISE_ENDPOINT!,
  apiKey: process.env.ENTERPRISE_API_KEY!,
});

const decision = await enterprise.authorization.check({
  organizationId: "org_demo",
  subjectId: "usr_example",
  action: "project:delete",
  resource: { type: "project", id: "project_123" },
});

asSession(token) returns a client that sends a user's session token instead of the service key.

Per-call options

Every method takes an optional last argument:

TypeScript
const controller = new AbortController();
await enterprise.organizations.get("org_demo", {
  signal: controller.signal,
  timeoutMs: 5000,
  retry: { maxAttempts: 5 },
});
Option Effect
signal Cancels the call and any retry wait. The call throws an error with code aborted.
timeoutMs Time limit for each attempt. The client default is 15000.
retry Retry policy for this call, or false for no retries.
idempotent true lets the retry policy apply to a call that would not retry by default. false turns retries off.

Retries

The client retries transport errors, timeouts, HTTP 429 and HTTP 503. It waits with exponential backoff and jitter. When the response has a Retry-After header, it waits that long instead. If Retry-After is longer than maxDelayMs, it stops and throws.

Retries apply by default to GET, PUT and DELETE requests. They also apply to these POST operations. Each one is read-only, or the runtime deduplicates it:

  • authorization.check
  • access.evaluate, access.batch and access.search
  • administration.loginRoute and administration.explain
  • audit.record and audit.ingest, which the runtime deduplicates by organization, source and event ID

Other POST and PATCH calls make one attempt. Pass idempotent: true only when a second attempt cannot cause a second effect. The runtime does not accept an Idempotency-Key header, so the client does not send one.

Set the default policy on the client:

TypeScript
const enterprise = new EnterpriseClient({
  endpoint,
  apiKey,
  retry: { maxAttempts: 3, baseDelayMs: 250, maxDelayMs: 20000 },
});

The values above are the defaults. Use retry: false to turn retries off.

Errors

Failed calls throw EnterpriseError:

Property Value
code The runtime error code, the SCIM scimType, or a client code
status The HTTP status, or 0 when no response arrived
message The server message, or a generic message
serverMessage The message from the error body, when the body has one
requestId The x-request-id response header, when present
cause The underlying error for transport failures and invalid responses

RuntimeErrorCode is the union of the runtime's error codes, and RUNTIME_ERROR_CODES lists them. ClientErrorCode covers transport_error, request_timeout, aborted, http_error and invalid_response.

TypeScript
import { EnterpriseError } from "@open-enterprise/sdk";

try {
  await enterprise.events.list("org_demo", { cursor });
} catch (error) {
  if (error instanceof EnterpriseError && error.code === "cursor_expired") {
    // Reconcile from a snapshot.
  }
}

Pagination

Methods whose names start with iterate return async iterators that follow next_cursor:

TypeScript
for await (const member of enterprise.organizations.iterateMembers(
  "org_demo",
)) {
  console.log(member.user_id);
}
Iterator Page method
organizations.iterateMembers organizations.members
audit.iterate audit.query
access.iterateSearch access.search
events.subscriptions.iterateDeliveries events.subscriptions.deliveries
administration.iteratePeople administration.people
administration.audit.iterate administration.audit.query
administration.audit.exportEvents administration.audit.exportPage

An iterator fetches the next page only when you ask for more items. iterateSearch yields resources, subject IDs or action names, depending on kind. iteratePeople yields people only. Read open invitations from administration.people.

Poll lifecycle events

EventPoller reads the event feed and follows the consumer rules in the repository's docs/events.md. You supply the storage:

TypeScript
import { EventPoller } from "@open-enterprise/sdk";

const poller = new EventPoller(enterprise, {
  organizationId: "org_demo",
  types: ["user.activated", "user.deactivated"],
  loadCursor: () => database.loadCursor(),
  receive: (batch) =>
    database.transaction(async (tx) => {
      for (const event of batch.events) await insertDurableInbox(tx, event);
      await saveCursor(tx, batch.cursor);
    }),
  onCursorExpired: () => database.markReconciliationRequired(),
});

const shutdown = new AbortController();
await poller.run({ signal: shutdown.signal });
  • receive must store the events and batch.cursor in one transaction, and resolve after the commit. The poller calls it for empty pages too, because they can move the cursor.
  • loadCursor runs before each page. Return null to start at the oldest retained event, or false to skip a poll while processing is paused.
  • An expired cursor calls onCursorExpired. The poller never resets the cursor. Without the callback, poll and run throw.
  • After a failure, run backs off from 500 ms up to 30 s. onError sees each failure. Throw from it to stop run.
  • When the runtime reports more events, run requests the next page at once. Otherwise it waits intervalMs, 1000 ms by default.
  • An abort stops run after the current receive call finishes.

poll() reads one page and returns { status, received, hasMore }.

Copy organizations, users and memberships

VendorSync keeps organizations, users and memberships in your own PostgreSQL database, so your app can join and list them and point foreign keys at them. Open Enterprise stays the source of truth. Change members and roles through its API, never by writing the copied tables.

TypeScript
import pg from "pg";
import { SYNC_SCHEMA_SQL, VendorSync } from "@open-enterprise/sdk/sync";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
await pool.query(SYNC_SCHEMA_SQL); // Once, for example in a migration.

const sync = new VendorSync({ client: enterprise, pool });
const shutdown = new AbortController();
void sync.run(shutdown.signal);

The service key needs events:read and profiles:read. SYNC_SCHEMA_SQL creates oe_organizations, oe_users, oe_memberships, oe_deleted_memberships and oe_sync_state. Apply it when upgrading an existing mirror. The deletion table stores each retired membership's organization, ID and version so that older feed entries cannot restore it. The pool can be a node-postgres Pool or anything with the same connect(), query() and release().

  • The first poll copies current state from GET /v1/events/state, then follows the vendor-wide feed. An expired cursor starts over from current state.
  • Recovery identifies a deleted membership by its organization and membership ID, even after retention removes the user details. Re-inviting the person creates a new membership with its own version.
  • Each page and its cursor are stored in one transaction. A change applies only when its resource version is newer than the stored one.
  • A membership can arrive before its user. The user row then holds only the ID until the profile follows.
  • run polls every 30 seconds, or at once while there is more. Call sync.wake() from the handler of an events.available webhook to poll sooner.
  • After a sign-in, sync.upsertLogin(await enterprise.asSession(token).me()) stores the user and membership, so the first request finds them. After a member API call, upsertMembership and removeMembership do the same. The feed applies the same change again later.

Prisma and Drizzle

Map the tables for queries; let SYNC_SCHEMA_SQL create them.

prisma
model OeUser {
  id            String         @id
  externalId    String?        @map("external_id")
  email         String?
  emailVerified Boolean?       @map("email_verified")
  displayName   String?        @map("display_name")
  memberships   OeMembership[]
  @@map("oe_users")
}

model OeMembership {
  organizationId    String  @map("organization_id")
  userId            String  @map("user_id")
  membershipId      String? @map("membership_id")
  role              String?
  status            String?
  active            Boolean
  membershipVersion BigInt  @map("membership_version")
  userVersion       BigInt  @map("user_version")
  user              OeUser  @relation(fields: [userId], references: [id])
  @@id([organizationId, userId])
  @@map("oe_memberships")
}

model OeOrganization {
  id      String  @id
  name    String?
  slug    String?
  version BigInt
  @@map("oe_organizations")
}
TypeScript
import { bigint, boolean, pgTable, primaryKey, text } from "drizzle-orm/pg-core";

export const oeOrganizations = pgTable("oe_organizations", {
  id: text("id").primaryKey(),
  name: text("name"),
  slug: text("slug"),
  version: bigint("version", { mode: "number" }).notNull(),
});

export const oeUsers = pgTable("oe_users", {
  id: text("id").primaryKey(),
  externalId: text("external_id"),
  email: text("email"),
  emailVerified: boolean("email_verified"),
  displayName: text("display_name"),
});

export const oeMemberships = pgTable(
  "oe_memberships",
  {
    organizationId: text("organization_id").notNull(),
    userId: text("user_id").notNull().references(() => oeUsers.id),
    membershipId: text("membership_id"),
    role: text("role"),
    status: text("status"),
    active: boolean("active").notNull(),
    membershipVersion: bigint("membership_version", { mode: "number" }).notNull(),
    userVersion: bigint("user_version", { mode: "number" }).notNull(),
  },
  (table) => [primaryKey({ columns: [table.organizationId, table.userId] })],
);

Verify webhooks

TypeScript
import { verifyWebhook } from "@open-enterprise/sdk/webhooks";

const event = await verifyWebhook({
  payload: rawRequestBody,
  headers: request.headers,
  secrets: configuredSigningSecrets,
});

Pass the raw body bytes, before any JSON parsing. The function checks the signature, the timestamp tolerance, the event ID and the envelope. It throws WebhookVerificationError when a check fails.

Typed request paths

The client builds each request from a path template and method in the OpenAPI document (src/schema.ts). A path or method that the document does not define fails tsc.

Development

Shell
npm test

npm test builds dist first, type-checks test/types.ts, and then runs the tests against the new build.

Publishing

npm publish runs prepack, which builds dist. The package publishes with public access and npm provenance. Provenance needs a CI job with an OIDC token, such as GitHub Actions with id-token: write. It also needs a repository field in package.json that matches the source repository.

Machine authentication

Service accounts are organization-owned principals. Use client.serviceAccounts to create accounts, assign independent credentials, rotate, disable or retire them. Their role assignments use { type: "service_account", id }, and their credential restrictions cap current resource permissions. A registration alone does not authorize machine access.

TypeScript
import { clientCredentials } from "@open-enterprise/sdk";

const token = await clientCredentials({
  issuer: "https://enterprise.example.com",
  clientId: serverConfig.clientId,
  clientSecret: serverConfig.clientSecret,
  organizationId: "org_example",
  resource: "https://app.example.com/api",
  scopes: ["projects:read"],
});

Keep client secrets on the automation backend. Machine grants return short-lived access tokens and issue no ID token or refresh token. Resources must validate audience, organization, typed principal and current access through introspection. For direct keys, construct a separate backend client with the presented key and call serviceAccounts.access for the current action and resource. API keys cannot become human sessions or trusted service credentials.

Search documentation