Skip to content

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.

Terminal window
npm install @zstrikehq/sdk

The package is ESM, ships TypeScript declarations, and requires Node.js ≥ 20 when running on Node.

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.

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.

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.

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');

client.entities covers the full entity surface of the Control Plane API:

// Single-entity CRUD
await 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 ingestion
const 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 sync
await client.entities.reconcile(allEntities);
await client.entities.reconcile([], { confirmEmpty: true }); // explicit mass-delete
// Validate against the project schema without writing
await 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 on 429 and 5xx with jittered backoff, honoring Retry-After. Single-entity mutations are never retried automatically. Prefer overwrite over JSON-Patch update in 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 just write.

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.

// Projects
const project = await client.projects.add({ name: 'billing' });
await client.projects.assignPdp(projectId, region); // attach to a shared PDP in a region
await client.projects.getPdp(projectId); // attachment + client token status
// Policies
const 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 first
await client.policies.analyze(projectId, { policyId, policy: candidateCedar }); // impact analysis
await client.policies.remove(projectId, policyId);
// Schema
const schema = await client.schema.get(projectId);
await client.schema.put(projectId, { description: 'Add Folder type', schema: newSchemaJson });
// Audit
await 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() and projects.update(projectId, …).
  • policies.getAll(projectId, { page, limit, search, status, sortBy, sortDir, metadataEquals }) returns { policies, meta }, where meta carries { page, limit, total }.
  • audit.getSummary({ projectId, … }) returns aggregate allow/deny counts (details).

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

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:

sync.ts
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:

Terminal window
export ZSTRIKE_APP_TOKEN=<project-scoped app token>
zstrike-sync run sync.ts --project prj_123 # incremental (delta) sync
zstrike-sync run sync.ts --project prj_123 --reconcile # full-state reconcile
zstrike-sync run sync.ts --project prj_123 --dry-run # print entities as NDJSON, push nothing

What 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 overwrite batches with the SDK’s retry policy.
  • Cursors — in delta mode, the cursor your fetch yields 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 0 on success and 1 if any entity failed. Dry-run NDJSON owns stdout, so you can pipe it.

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:

Terminal window
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.