⚠️ Porta is in beta — APIs and features may change before v1.0
Skip to content

TypeScript SDK

The @portaidentity/sdk package provides a universal TypeScript client for the Porta Admin API. It works in Node.js, browsers, and AI agent environments.

Installation

bash
yarn add @portaidentity/sdk
# or
npm install @portaidentity/sdk

The package is located at packages/porta-sdk/ in the monorepo.

Quick Start (Node.js)

typescript
import { createPortaClient } from '@portaidentity/sdk';
import { createNodeTransport, createTokenAuth } from '@portaidentity/sdk/node';

const transport = createNodeTransport({
  baseUrl: 'https://porta.local:3443/api/admin',
  auth: createTokenAuth('your-bearer-token'),
});

const porta = createPortaClient({ transport });

// List organizations
const orgs = await porta.organizations.list();
console.log(orgs.data);

// Create a user (OIDC given/family name fields)
const user = await porta.users.create({
  organizationId: 'org-id',
  email: 'alice@example.com',
  givenName: 'Alice',
  familyName: 'Smith',
});

Quick Start (Browser)

typescript
import { createPortaClient } from '@portaidentity/sdk';
import { createBrowserTransport, createTokenAuth } from '@portaidentity/sdk/browser';

const transport = createBrowserTransport({
  baseUrl: '/api/admin',
  auth: createTokenAuth(sessionToken),
});

const porta = createPortaClient({ transport });
const stats = await porta.stats.get();

Entrypoints

Import PathPurposeEnvironment
@portaidentity/sdkClient factory, types, errors, paginationUniversal
@portaidentity/sdk/nodeNode.js transport, all auth providersNode.js
@portaidentity/sdk/browserFetch-based transport, token authBrowser
@portaidentity/sdk/agentAI agent tool definitions & executorAI agents

Authentication Providers

Bearer Token

typescript
import { createTokenAuth } from '@portaidentity/sdk/node';
const auth = createTokenAuth('your-token');

Client Credentials (M2M)

typescript
import { createClientCredentialsAuth } from '@portaidentity/sdk/node';
const auth = createClientCredentialsAuth({
  tokenEndpoint: 'https://porta.local:3443/super-admin/oidc/token',
  clientId: 'my-client-id',
  clientSecret: 'my-client-secret',
});

CLI Auth (stored credentials)

typescript
import { createCliAuth } from '@portaidentity/sdk/node';
const auth = createCliAuth({
  credentialsPath: '~/.porta/credentials.json',
  refreshEndpoint: 'https://porta.local:3443/super-admin/oidc/token',
  clientId: 'porta-admin-cli',
});

Domain Namespaces

The PortaClient provides 20 domain namespaces:

NamespaceDescriptionKey Methods
organizationsOrg CRUD, status lifecycle, destroylist, get, create, update, suspend, activate, archive, destroy
applicationsApp CRUD, moduleslist, get, create, update, archive, listModules, addModule
clientsClient CRUD, secretslist, get, create, update, revoke, generateSecret
usersOrg-scoped user CRUD, invite, password, status, GDPRlist, get, create, invite, invitePreview, setPassword, clearPassword, verifyEmail, suspend, unsuspend, deactivate, reactivate, lock, unlock, exportData, purge
usersByIdOrg-less user ops (Admin GUI SPA)get, update, suspend, unsuspend, activate, verifyEmail, getHistory
rolesApplication roles, permission mappinglist, get, create, update, assignPermission, removePermission
permissionsApplication permissionslist, get, create, archive
userRolesUser-role assignmentslist, assign, remove
customClaimsClaim definitionslist, get, create, update, archive
userClaimsUser claim valueslist, set, remove
configSystem configurationlist, get, set
keysSigning key managementlist, generate, rotate
auditAudit loglist, listAll
statsDashboard statisticsget, getOrganizationStats
sessionsSession managementlist, revoke, revokeForUser
bulkBulk status operationsexecute
brandingOrg branding & assetsgetSettings, updateSettings, uploadAsset
exportsCSV/JSON data exportdownload
twoFactor2FA admin management (user + org)getStatus, disable, reset, regenerateRecoveryCodes, getPolicy, setPolicy, getSummary
importsDeclarative provisioningprovision

The users domain mirrors the org-scoped user routes; usersById mirrors the org-less standalone user routes used by the Admin GUI SPA. stats.get() returns the system-wide StatsOverview (GET /stats/overview), and stats.getOrganizationStats(orgId) returns per-org OrgStats.

ETag / Optimistic Concurrency

The get() method on core entities returns { data, etag }. Pass the etag to update() for safe concurrent writes:

typescript
const { data: org, etag } = await porta.organizations.get('my-org');
const updated = await porta.organizations.update('my-org', { name: 'New Name' }, etag);

If the entity was modified since you read it, a PortaConflictError (HTTP 409) is thrown.

Pagination

List methods return PaginatedResponse<T> with data, total, page, pageSize, and optional cursor. Use listAll() for automatic cursor-based iteration:

typescript
// Manual pagination
const page1 = await porta.organizations.list({ page: 1, pageSize: 10 });

// Auto-paginate all results
const allOrgs = await porta.organizations.listAll();

Error Handling

All API errors throw typed error classes:

Error ClassHTTP StatusDescription
PortaAuthenticationError401Invalid or expired credentials
PortaForbiddenError403Insufficient permissions
PortaNotFoundError404Resource not found
PortaValidationError422Invalid input (with field details)
PortaConflictError409ETag mismatch or duplicate
PortaRateLimitError429Rate limit exceeded
PortaServerError5xxServer error
typescript
import { PortaNotFoundError, PortaValidationError } from '@portaidentity/sdk';

try {
  await porta.organizations.get('nonexistent');
} catch (err) {
  if (err instanceof PortaNotFoundError) {
    console.log('Not found:', err.message);
  }
  if (err instanceof PortaValidationError) {
    console.log('Validation errors:', err.details);
  }
}

AI Agent Integration

The @portaidentity/sdk/agent entrypoint provides tool definitions compatible with LLM function-calling:

typescript
import { getToolDefinitions, executeTool } from '@portaidentity/sdk/agent';

// Get all available tools for the AI model
const tools = getToolDefinitions();

// Execute a tool from AI agent output
const result = await executeTool(porta, 'organizations.list', { pageSize: 10 });

Architecture

The SDK uses a layered architecture:

  1. Transport layer — HTTP abstraction (Node.js http/https or browser fetch)
  2. Auth layer — Pluggable authentication providers (token, client credentials, CLI)
  3. Domain layer — 20 domain namespaces mapping to Admin API endpoints
  4. Client factory — Composes transport + domains into a single PortaClient
  5. Agent layer — Tool definitions + executor for AI integration

All layers are ESM-only, tree-shakeable, and fully typed with TypeScript declarations.

Released under the MIT License.