TypeScript
@zstrikehq/sdk is the official TypeScript SDK for ZStrike. One package provides:
ZStrikeClient— a typed client for authorization checks against your PDP and entity management against the Control Plane API;- an entity builder — a fluent API for constructing valid Cedar entities;
zstrike-sync— a CLI that turns one small file you write into a complete entity sync job, with batching, retries, cursors, and dry runs handled for you.
The SDK is server-side only — it authenticates with secrets that must never reach a browser. The library runs on Node.js 20+ and edge runtimes (Cloudflare Workers, Vercel Edge, Deno); the CLI requires Node.js.
Install
Section titled “Install”npm install @zstrikehq/sdkThe package is ESM, ships TypeScript declarations, and requires Node.js ≥ 20 when running on Node.
Configuration
Section titled “Configuration”Every setting can be passed to the constructor or read from an environment variable (constructor wins). There are two independent credential sets — configure only what you use:
| Purpose | Constructor option | Environment variable |
|---|---|---|
| PDP base URL (authorization) | pdpUrl |
ZSTRIKE_PDP_URL |
| PDP client token | clientToken |
ZSTRIKE_CLIENT_TOKEN |
| Control Plane base URL (entities) | papUrl |
ZSTRIKE_PAP_URL |
| App token (entities) | appToken |
ZSTRIKE_APP_TOKEN |
| Project ID (entities) | projectId |
ZSTRIKE_PROJECT_ID |
The Control Plane URL defaults to the hosted API, https://api.zstrike.io (pinned to API version v2026-01); set papUrl only for self-hosted or test environments. The PDP URL has no default.
Further options: authorizeTimeoutMs (default 2000), managementTimeoutMs (default 10000), maxRetries (default 2; entity ingest calls default to 3 when unset), and fetch to inject a custom fetch implementation. HTTPS is enforced for both base URLs (allowInsecureHttp: true relaxes this for local development).
Configuration is validated lazily: constructing a client never throws, and the first call that needs a missing value fails with a ConfigurationError naming the exact variable to set.
Authorizing requests
Section titled “Authorizing requests”import { ZStrikeClient } from '@zstrikehq/sdk';
const client = new ZStrikeClient();
const result = await client.authorize( 'App::User::"alice"', 'App::Action::"read"', 'App::Document::"doc123"', { mfa_verified: true }, // optional context { userJwt: request.token }, // optional end-user JWT for trusted-provider validation);
if (!result.allowed) { // result.reason — the policy IDs that determined the decision throw new ForbiddenError();}Principal, action, and resource accept Cedar UID strings (App::User::"alice") or objects ({ type: 'App::User', id: 'alice' }).
The options argument also accepts entities: an inline copy of the resource and its ancestors, for resources not yet synced to the platform. The SDK then sends your app token as X-App-Token, and that token needs the inline_entities grant. See inline resource entities.
A Deny is a result, not an exception. AuthorizeResult carries decision ('Allow' | 'Deny'), the convenience boolean allowed, reason (determining policy IDs), and errors (per-policy evaluation errors). Exceptions are reserved for real failures — misconfiguration, network errors, bad tokens — which is exactly the fail-closed handling you want around an authorization check.
Bulk permissions
Section titled “Bulk permissions”client.permissions() calls the PDP’s bulk permissions endpoint. In one call it tells you which actions a principal may take on a resource, for gating UI:
const { decisions } = await client.permissions( 'App::User::"alice"', 'App::Document::"doc123"', { actions: ['read', 'update', 'share'] }, // short action IDs; omit to evaluate all);if (decisions.share) showShareButton();It also accepts context and userJwt in the options. It emits no audit events, so keep authorize() on the code path that performs the operation.
Building entities
Section titled “Building entities”The builder constructs entities in the platform’s Cedar JSON shape and rejects structurally invalid input (empty types, IDs, or attribute keys) at build time:
import { Entity } from '@zstrikehq/sdk';
const user = Entity.create('App::User', 'alice') .attr('email', 'alice@example.com') .attr('department', 'engineering') .parent('App::Team', 'engineering') .build();// { uid: { type: 'App::User', id: 'alice' }, attrs: { … }, parents: [ … ] }For batch operations there are matching builders for the other operation types:
const patch = Entity.update('App::User', 'alice') .replace('department', 'platform') .addParent('App::Team', 'platform') .build();
const removal = Entity.delete('App::User', 'mallory');Managing entities
Section titled “Managing entities”client.entities covers the full entity surface of the Control Plane API:
// Single-entity CRUDawait client.entities.create(user);await client.entities.update(user);await client.entities.delete('App::User::"mallory"');const page = await client.entities.list({ page: 1, limit: 100 });
// Bulk ingestionconst result = await client.entities.batch([ { operation: 'overwrite', uid: user.uid, attrs: user.attrs, parents: user.parents }, Entity.delete('App::User', 'mallory'),]);// result.successCount, result.failureCount, per-item results and errors
// Declarative full-state syncawait client.entities.reconcile(allEntities);await client.entities.reconcile([], { confirmEmpty: true }); // explicit mass-delete
// Validate against the project schema without writingawait client.entities.validate(candidateEntities);Semantics worth knowing:
- Batches auto-chunk. Pass any number of operations; the SDK splits them into requests of 250 (the API limit) and merges the per-item results back into your original order.
- Retries respect idempotency. Reads and ingest calls (
batch,reconcile) retry on429and5xxwith jittered backoff, honoringRetry-After. Single-entity mutations are never retried automatically. Preferoverwriteover JSON-Patchupdatein sync jobs — overwrite is safe to retry, patches are not. - Deletes need the grant. Operations that delete entities require an app token with
entities: delete, not justwrite.
Managing projects, policies, schema, and audit
Section titled “Managing projects, policies, schema, and audit”The same client covers the rest of the Control Plane API that app tokens can reach. Each call needs the matching permission grant.
// Projectsconst project = await client.projects.add({ name: 'billing' });await client.projects.assignPdp(projectId, region); // attach to a shared PDP in a regionawait client.projects.getPdp(projectId); // attachment + client token status
// Policiesconst created = await client.policies.add(projectId, { description: 'Engineers can read design docs', policy: 'permit (principal in App::Team::"engineering", action == App::Action::"read", resource in App::Folder::"design-docs");', status: 'ACTIVE',});await client.policies.update(projectId, policyId, { /* same shape */ });await client.policies.getById(projectId, policyId);await client.policies.getVersions(projectId, policyId); // append-only history, newest firstawait client.policies.analyze(projectId, { policyId, policy: candidateCedar }); // impact analysisawait client.policies.remove(projectId, policyId);
// Schemaconst schema = await client.schema.get(projectId);await client.schema.put(projectId, { description: 'Add Folder type', schema: newSchemaJson });
// Auditawait client.audit.getEvents({ projectId, decision: 'deny', pageSize: 50 });Retry behavior follows idempotency. policies.update and policies.remove are retried on transient failures. policies.add is never retried automatically, because a retried timeout could create a duplicate policy.
New in 0.4.0 (the npm release is currently 0.2.0):
projects.list()andprojects.update(projectId, …).policies.getAll(projectId, { page, limit, search, status, sortBy, sortDir, metadataEquals })returns{ policies, meta }, wheremetacarries{ page, limit, total }.audit.getSummary({ projectId, … })returns aggregate allow/deny counts (details).
Errors
Section titled “Errors”All errors extend ZStrikeError (with status and the response body when available):
| Error | Raised on |
|---|---|
ConfigurationError |
Missing/invalid configuration, bad sync module |
AuthenticationError |
401 — expired or revoked token; rotate it |
PermissionError |
403 — the token lacks the required grant |
NotFoundError |
404 |
ValidationError |
400, malformed UIDs, empty batches |
RateLimitError |
429, with retryAfterSeconds |
ServerError / TransportError |
5xx / network failures |
BuilderError / InvalidEntityError |
Invalid builder usage / entity shape |
Continuous sync with zstrike-sync
Section titled “Continuous sync with zstrike-sync”Instead of hand-rolling an ingestion job, write one file with up to two functions — fetch (read rows from your system) and transform (map a row to entities) — and let the CLI do the rest:
import { Entity, defineSync } from '@zstrikehq/sdk';
export default defineSync({ async *fetch(cursor) { const rows = await db.query( 'SELECT * FROM users WHERE updated_at > $1 ORDER BY updated_at', [cursor ?? 0], ); yield { rows, cursor: rows.at(-1)?.updated_at }; }, transform: (row) => Entity.create('App::User', row.id) .attr('email', row.email) .parent('App::Org', row.org_id) .build(),});Run it:
export ZSTRIKE_APP_TOKEN=<project-scoped app token>
zstrike-sync run sync.ts --project prj_123 # incremental (delta) synczstrike-sync run sync.ts --project prj_123 --reconcile # full-state reconcilezstrike-sync run sync.ts --project prj_123 --dry-run # print entities as NDJSON, push nothingWhat the CLI handles for you:
- Validation — every transformed entity is checked against the required shape before anything is pushed.
- Batching and retries — pages are pushed as idempotent
overwritebatches with the SDK’s retry policy. - Cursors — in delta mode, the cursor your
fetchyields is persisted to.zstrike-sync-cursor.json(configurable via--cursor-file) after each page is pushed successfully, so an interrupted run resumes where it left off. Reconcile and dry runs never touch the cursor. - Safety — a reconcile that would delete everything (zero entities) is refused unless you pass
--confirm-empty. - Scriptability — a JSON summary (mode, batches, entities, success/failure counts) is written to stderr; exit code is
0on success and1if any entity failed. Dry-run NDJSON owns stdout, so you can pipe it.
File input
Section titled “File input”Have a file instead of a live source? Skip fetch entirely and point the CLI at a .json array or .ndjson file — rows still flow through your transform:
zstrike-sync run sync.ts --project prj_123 --input users.ndjson| Flag | Description |
|---|---|
--project <id> |
Project ID (or ZSTRIKE_PROJECT_ID) |
--token <token> |
App token. Discouraged: it shows up in the process list and shell history. Prefer ZSTRIKE_APP_TOKEN, which is read automatically. |
--base <url> |
Control Plane base URL (or ZSTRIKE_API_BASE / ZSTRIKE_PAP_URL); defaults to the hosted API |
--reconcile |
Full-state reconcile instead of delta sync |
--dry-run |
Build and print entities; no network, no cursor writes |
--input <file> |
Read rows from a .json array or .ndjson file |
--out <file> |
Write dry-run NDJSON to a file instead of stdout |
--cursor-file <file> |
Cursor location (default .zstrike-sync-cursor.json) |
--confirm-empty |
Allow a reconcile with zero entities |
--insecure |
Allow http:// base URLs (local development only) |
TypeScript sync modules run under tsx (npx tsx node_modules/@zstrikehq/sdk/dist/cli.js run sync.ts); plain .js/.mjs modules run directly. In containers, the whole job is one line in any Node 20+ image.