Skip to content

TypeScript SDK reference

Audience: TypeScript / JavaScript engineers integrating Nanorix into a Node.js backend or modern bundler-built browser app. Package: @nanorix/sdk (v0.7.0). The 1.0 contract freeze is planned; the current surface is stable and additive. Node: 20.19+ on 20.x or 22.12+ · TypeScript: 5.x · ES Modules + CommonJS dual export. Substrate framing. The SDK wraps the HTTP API documented in api-reference.md. Surface is byte-symmetric with the Python SDK: every method has the same name (camelCase instead of snake_case), the same arguments, the same return shape, the same exception hierarchy. The top-level differences: the client class (nanorix.Client in Python, NanorixClient in TypeScript), no close() and no async client in TypeScript, and timeouts in milliseconds in TypeScript and seconds in Python.


Install

npm install @nanorix/sdk

Or from source: github.com/nanorix-io/nanorix-sdk.

Dependencies: zero runtime deps for crypto (uses Node crypto builtins for HMAC, signatures, hashing).


Top-level surface

import { NanorixClient } from "@nanorix/sdk";

// Construction
const client = new NanorixClient({ apiKey: "nrx_live_your_key_here_0000" });
const client2 = new NanorixClient({ apiKey: process.env.NANORIX_API_KEY! }); // apiKey is required; no environment variable is read for you
const client3 = new NanorixClient({ apiKey: process.env.NANORIX_API_KEY!,
                              baseUrl: "https://api.nanorix.io",
                              timeout: 30000, maxRetries: 3 }); // these three are the defaults

// Resources
client.capsulefiles      // Capsulefile lifecycle
client.capsules          // capsule lifecycle + .run(), .batch(), .session()
client.cdp               // AuditProof retrieval (alias: client.auditProofs)
client.auditProofs       // alias of .cdp
client.egressProfiles    // named egress allowlists
client.usage             // usage summary, line-items, CSV export
client.webhooks          // webhook endpoints + deliveries

// Subpackage namespaces
import { verifyAuditProof, type VerifierPolicy } from "@nanorix/sdk";
import { HipaaContext, GdprContext, Soc2Context } from "@nanorix/sdk";

// Top-level
await client.health();    // GET /v1/health

The default baseUrl, https://api.nanorix.io, is the hosted Evaluation Sandbox, for data that is not regulated. For regulated data, set baseUrl to your own BYOC deployment (self-hosting), for example new NanorixClient({ apiKey: process.env.NANORIX_API_KEY!, baseUrl: "https://nanorix.internal.example.com" }).

The timeout default of 30000 ms bounds the wait for each attempt's response headers; reading the body has no timeout. Uploads use 300 s and exec uses 600 s whatever timeout is. On Node.js the built-in fetch also stops waiting for response headers after 300 s by default, which caps the exec wait at 300 s. A client holds no open transport, so there is no close() to call.

The SDK is async-first; every method returns a Promise. The SDK exports one client class, NanorixClient. There is no separate async client and no Client or AsyncClient symbol, because Node-side TypeScript is async by default.


Exceptions

Full reference: error catalog.

import {
  NanorixError,                       // base
  AuthenticationError,                // 401
  NotFoundError,                      // 404
  ConflictError,                      // 409
  BadRequestError,                    // 400
  QuotaExceededError,                 // 402, 403 (quota)
  PayloadTooLargeError,               // 413
  GoneError,                          // 410: lifetime ended before the destroy, or capsule no longer live (below)
  RateLimitError,                     // 429 (after the retry budget, or at once when not retried)
  UnprocessableEntityError,           // 422 default
  InputProvenanceRejectedError,       // 422 input_provenance_rejected
  SecretsInjectionRejectedError,      // 422 secrets_injection_rejected
  ExecutionError,                     // non-zero exit; .cdp set only in the cases below
  CeilingError,                       // not thrown: see "When a capsule's lifetime ends" below
  TimeoutError,                       // not thrown: an exec timeout within the exec wait (300 s on Node.js's built-in fetch) throws ExecutionError, exitCode -1
} from "@nanorix/sdk";

When a capsule's lifetime ends. An exec sent after the capsule's lifetime (maxLifetimeSeconds) ends throws GoneError (410) while the capsule is not destroyed yet, and ConflictError (409) once it is; a command still running when the lifetime ends can come back with exit code -1 (ExecutionError). upload(), listOutputs() and download() throw GoneError once the capsule is no longer live, for example after a destroy. In the 410 window no AuditProof exists yet: capsule.destroy() returns it, or the lifetime reaper destroys the capsule later. client.cdp.get(capsuleId) throws NotFoundError until the proof is stored, including while the destroy is pending. A NanorixError that run(), batch() or session() throws after creating the capsule carries the capsule's id as capsuleId, and the capsule's AuditProof as cdp when their cleanup destroy succeeded (below). A lifetime end after their exec throws the GoneError unchanged.

When an error's cdp, capsuleId and cleanupError are set. Every NanorixError has capsuleId, cdp and cleanupError, undefined unless set. When run(), batch() or session() throw a NanorixError after creating the capsule, they destroy the capsule, set capsuleId, and set cdp to its AuditProof when that destroy succeeds. The three name one capsule: an error that already carries a proof is left as it is, and one whose capsuleId names another capsule gets no proof and no cleanupError. In those two cases the error does not name the capsule the call created; client.capsules.list() finds it. When that destroy fails, or the error came from their final destroy, the error carries capsuleId and no cdp; the list after this paragraph says what to do. When that destroy failed with a NanorixError, the error also carries that destroy's own error as cleanupError, unless it already carries one, so you can read its statusCode and body: a 503 auditproof_signing_unavailable there (AuditProofSigningUnavailableError, with retrySigningUrl and pauseWindowExpiresAt) means the capsule's status is signing_failed, so POST retry-signing as the list's first item says, without reading the status first. A thrown value that is not a NanorixError, such as one your onRecord callback throws, is thrown unchanged, without the id or the proof. batch() and session() throw ExecutionError with exitCode 0 when the capsule did not write results.jsonl or state.bin (the download answered 404; that NotFoundError is its cause); any other failed download is thrown unchanged. ExecutionError.cdp is also set when a batch() with onRecordError: "abort_batch" stops on a record error (if that destroy fails, its error is thrown instead of ExecutionError).

When an error carries capsuleId and no cdp, read client.capsules.get(capsuleId) and act on its status:

  • signing_failed: POST, with a developer key or above, to the path /v1/capsules/{capsuleId}/retry-signing before the pause window ends. A 503 auditproof_signing_unavailable means signing is still unavailable and the window started again: POST again before the pause_window_expires_at its body gives. A 409 naming a signing buffer overflow means POST again later. A 500 saying the capsule cannot be retried means retry-signing cannot complete its proof.
  • volatile_destroyed or destroyed_pending_cdp: the destroy is still running; read the status again shortly.
  • active or executing: the capsule was not destroyed and still holds its data; destroy it.
  • expired, or the read throws GoneError: the capsule is past its lifetime and the reaper destroys it; read the status again later.
  • destroyed: client.cdp.get(capsuleId) returns the proof.
  • destroyed_no_proof or expired_unclean: no destroy or retry-signing request you send produces a proof for it.

An exec's timeout ends the command on the server, unless the capsule's lifetime (max_lifetime_seconds) ends it first. execute() waits for the exec's response for that timeout (seconds) plus 60 seconds and never less than 600 seconds, whatever the client's own timeout is; without an exec timeout, execute() waits up to 600 seconds for the exec's response, so give a command that may run longer a timeout. On Node.js, the built-in fetch stops waiting for response headers after 300 seconds by default and the SDK sets no dispatcher of its own, so there the wait is at most 300 seconds, and an exec whose response takes longer throws NanorixError at once (HTTP error: fetch failed) and is not sent again. When the command ends within that wait, a nonzero exit throws ExecutionError, and an exec stopped by its timeout comes back with exitCode -1. The SDK sends these requests again on each retry (three by default) after a timeout, a network error or a 429, 500, 502, 503 or 504: a GET or HEAD, and a capsule or capsulefile create carrying an Idempotency-Key that matches [A-Za-z0-9_-]{1,255} (the SDK adds one when you pass none). A create retried after the first create has finished returns that capsule or Capsulefile; a create retried while the first is still running, or after a 5xx, can create a second one. Any request is sent again when its connection failed before it was sent (fetch failed with cause code ECONNREFUSED, ENOTFOUND, EAI_AGAIN or UND_ERR_CONNECT_TIMEOUT), and any request to /v1/capsules or /v1/capsulefiles or a path under them, an exec, an upload, a record commit (POST /v1/capsules/:id/record) and a destroy among them, is sent again after a 429 once it has waited out the 429's Retry-After, because on those paths the API's rate limiters answer before the request is handled. Every request other than a GET, a HEAD or a keyed create, an exec, a record commit and a destroy among them, is not sent again after a timeout, a network error once it may have been sent, or a 500, 502, 503 or 504: the SDK throws NanorixError at once, with the response's statusCode when there was one, and its message says the request may have reached the server and was not sent again, and for an exec that the command may have run (not when the exec's 503 carries the error code isolation_unavailable, which means the command was not run). The exception is a destroy's 503 auditproof_signing_unavailable, which throws AuditProofSigningUnavailableError as before. Outside those paths, a 429 on a request other than a GET or a HEAD throws RateLimitError at once, with its retryAfter and the same message. withRetry does not send again a request the SDK threw that message for, nor one that threw AuditProofSigningUnavailableError. A proxy or load balancer in front of your deployment with a shorter request timeout answers first, often with 504, and the SDK throws that answer to an exec the same way.

Every exception carries statusCode?: number and body?: Record<string, unknown>. The body.error.request_id field is the support-ticket correlation id; quote it when filing.


client.capsulefiles

Class: Capsulefiles.

create(opts)

async create(opts: {
  name: string;
  runtime: string;
  entrypoint: string;
  files: string[] | Record<string, Buffer | Uint8Array>;   // required
  description?: string;
  labels?: Record<string, string>;
  env_vars?: Record<string, string>;
  capsule_memory_mb?: number;
  input_path?: string;
  output_path?: string;
  egress_declaration?: string[];
  idempotencyKey?: string;
}): Promise<Capsulefile>

Maps to POST /v1/capsulefiles (+ POST /:id/files + POST /:id/finalize). The body option names are snake_case, as the API takes them; idempotencyKey, which goes in a header, is the one camelCase option. The call always finalizes.

capsule_memory_mb is the memory for each capsule created from this Capsulefile, in MB. This call stores the value as given; the validate and cost-estimate endpoints (nanorix capsulefiles validate, nanorix capsulefiles estimate-cost) accept 64 to 32768. At capsule create (POST /v1/capsules), a value above your tier's ceiling (none on an install with billing off) is refused with 400 invalid_parameters, and a value above the server's per-capsule limit with 400 capsule_memory_exceeds_server_limit; neither is lowered to fit. Omit it to get the smaller of your tier's ceiling and the server's limit. The POST /v1/capsules response carries the limit the runtime wrote as memory_limit_bytes, which client.capsules.create() does not expose: for const capsule = await client.capsules.create(...), read (await client.capsules.get(capsule.id)).memory_limit_bytes (typed unknown), which is present only when the API server process that answers runs the capsule.

labels is sent by the SDK, but the API does not store labels today, so the Capsulefile's labels reads back {}.

This method has no dataClassification, defaultTtl, packages, finalize or memoryMb option, and no camelCase form of the body options (envVars, egressDeclaration and the like are not read). There is no install step: bundle the packages' files in files, or use nanorix build, which does that from packages:.

Example:

const cf = await client.capsulefiles.create({
  name: "med-ai-extraction",
  runtime: "python3.12",
  entrypoint: "python /data/input/capsulefile/main.py",
  files: ["main.py"],
  egress_declaration: ["api.anthropic.com"],
  capsule_memory_mb: 512,
  env_vars: { ANTHROPIC_MODEL: "claude-3-5-sonnet-latest" },
});
console.log(cf.id, cf.content_hash);

idempotencyKey (optional) is sent as the Idempotency-Key header of POST /v1/capsulefiles; when omitted the SDK generates a UUIDv4 once per call and sends it on every retry. A retry after the first create has finished returns that Capsulefile; a retry sent while the first is still running, or after a 5xx, can create a second one. The key must match [A-Za-z0-9_-]{1,255}; the SDK treats a create whose key does not match like a create without a key, so it is not sent again after a timeout, a network error once the request may have been sent, or a 5xx. It is still sent again after a connection that failed before sending, and after a 429.

list(params) / get(id) / delete(id)

async list(params?: Record<string, string>): Promise<CapsulefileList>
async get(capsulefileId: string): Promise<Capsulefile>
async delete(capsulefileId: string): Promise<void>

update(id, fields)

Not available: it rejects with an Error.

waitUntilFinalized(id, opts)

Polls get() until the status is finalized. create() finalizes before it returns and gives back the finalized record, so this is for waiting on a Capsulefile another process is finalizing.

async waitUntilFinalized(id: string, opts?: { timeout?: number; pollInterval?: number }): Promise<Capsulefile>

Both options are in milliseconds. timeout defaults to 120000 and pollInterval to 2000.

uploadDir(id, dirPath)

Uploads every file under dirPath recursively. Returns the file count.

async uploadDir(capsulefileId: string, dirPath: string): Promise<number>

client.capsules

Class: Capsules.

create(opts)

async create(opts?: {
  capsulefile?: string;
  maxLifetimeSeconds?: number;
  egressProfile?: string;
  metadata?: Record<string, string>;
  dataClassification?: string;
  jurisdiction?: string;
  label?: string;
  cdpKind?: "workload" | "call" | "request" | "batch";
  declareActivity?: boolean;
  parentCdpId?: string;
  signingMode?: "nanorix_only" | "customer_only";
  idempotencyKey?: string;
}): Promise<LiveCapsule>

Maps to POST /v1/capsules. metadata carries customer-declared context in the AuditProof as given; the capsule_started event (signed on 2.1 and 2.2) carries its metadata_hash; no shipped verifier compares the two (16 keys max, 64-char keys, 256-char values, 4 KB total; nanorix:* prefix reserved).

dataClassification (sent as data_classification) is your declaration of the data the capsule handles: PHI, PII, financial, credentials or general, in any letter case. The SDK sends it as given; the API refuses any other value with HTTP 400 and records it, lowercased, as capsule_context.data_classification in the capsule's AuditRecord, outside the AuditProof's signature. Nanorix does not check it against the data. When you omit it the SDK sends nothing and the API records general.

jurisdiction (sent as jurisdiction) is your declaration of the capsule's jurisdiction: us, ca, gb, au, in, eu-fr, eu-de or eu-nl. The SDK sends it as given; the API lowercases it, refuses any other value with HTTP 400 (invalid_parameters, with a message starting invalid_jurisdiction) and records it as the AuditProof's jurisdiction, under its signature. When you omit it the SDK sends nothing and the API records your account's declared jurisdiction where that names one country (US is us, UK is gb, CA is ca, AU is au, IN is in); for an account declared EU or OTHER it refuses the create with HTTP 400 (invalid_parameters, with a message starting invalid_jurisdiction), so name one. It is separate from your organization's jurisdiction, declared at signup or by an organization admin, which the AuditRecord's capsule_context.jurisdiction and regulatory_context use.

label (sent as label) is an optional name for the capsule, stored with it. cdpKind (sent as cdp_kind) is the AuditProof scope: workload (the default when absent), call, request or batch, recorded as given and placed under the AuditProof's signature.

run(opts)

async run(opts: {
  capsulefile: string;
  inputs?: Record<string, Buffer>;
  command?: string;
  timeout?: number;
  maxLifetimeSeconds?: number;
  metadata?: Record<string, string>;
  dataClassification?: string;
  jurisdiction?: string;
  label?: string;
  egressProfile?: string;
  cdpKind?: "workload" | "call" | "request" | "batch";
  declareActivity?: boolean;
  idempotencyKey?: string;
}): Promise<[Record<string, Buffer>, CdpAccess]>

Returns the tuple [outputs, cdp]. The create options go to create() unchanged; one you omit is not sent.

One-shot lifecycle: create → upload → execute → download → destroy.

Example (Pattern 3, single-shot extraction):

import * as fs from "node:fs";

const [outputs, cdp] = await client.capsules.run({
  capsulefile: "cf_aB3dE9xQ",
  inputs: { "input.pdf": fs.readFileSync("test.pdf") },
  metadata: { matter_id: "ACME-001" },
  dataClassification: "PII",
});
console.log(Object.keys(outputs));
console.log("capsule id:", cdp.id);
console.log("document_hash:", cdp.verification().document_hash);

batch(opts)

Anthropic-Batches-shape batch processing with RFC 6962 Merkle-root client-side (byte-equivalent to Rust runtime + Python SDK).

async batch(opts: {
  capsulefile: string;
  records: Iterable<Record<string, unknown>>;
  onRecord?: (record: BatchRecord) => void;
  recordIdField?: string;        // default "custom_id"
  onRecordError?: "fail_isolated" | "abort_batch";   // default "fail_isolated"
  maxLifetimeSeconds?: number;
  metadata?: Record<string, string>;
  timeout?: number;
  dataClassification?: string;
  jurisdiction?: string;
}): Promise<BatchResult>

BatchResult carries merkleRoot, auditProof, records, successCount, errorCount. Customer entrypoint reads /data/input/records.jsonl and writes /data/output/results.jsonl per the same wire shape as the Python SDK.

session(opts)

LangGraph-shape stateful session-mode for multi-capsule reasoning chains. Customer-managed encrypted state continuity via parentCdpId.

async session(opts: {
  capsulefile: string;
  sessionId: string;
  parentCdpId?: string;
  initialState?: Buffer;
  maxLifetimeSeconds?: number;
  metadata?: Record<string, string>;
  timeout?: number;
  dataClassification?: string;
  jurisdiction?: string;
}): Promise<SessionResult>

list(params) / get(id)

Standard list/get.

LiveCapsule workspace methods

LiveCapsule is the handle returned by create(). Methods:

Method Maps to
.id (property) capsule id
.status (property) current status
.upload(filename, data) POST /v1/capsules/:id/upload?filename=...
.execute(command?, { timeout? }) POST /v1/capsules/:id/exec
.listOutputs() GET /v1/capsules/:id/output
.download(filename) GET /v1/capsules/:id/output/:filename
.destroy() → CdpAccess DELETE /v1/capsules/:id
.refresh() GET /v1/capsules/:id

Workspace-mode example:

const capsule = await client.capsules.create({ capsulefile: "cf_aB3dE9xQ" });
await capsule.upload("input.pdf", pdfBytes);
const result = await capsule.execute("python /data/input/capsulefile/main.py", { timeout: 60 });
console.log(result.stdout);

// Iterate without re-uploading
const result2 = await capsule.execute("python /data/input/capsulefile/main.py --verbose");

// Destroy and get the AuditProof
const cdp = await capsule.destroy();
console.log(cdp.verification().document_hash);

client.cdp (alias: client.auditProofs)

Class: CdpResource.

async get(capsuleId: string): Promise<CdpAccess>
async verify(capsuleId: string): Promise<AuditProof>   // the verification proof object

get() retrieves the full proof (GET /v1/capsules/:id/cdp); verify() retrieves the AuditProof summary projection (GET /v1/capsules/:id/cdp/verify?format=presentation). For the canonical offline-verifiable document, use downloadAuditProof from nanorix/debug or fetch the endpoint without the format parameter.

CdpAccess exposes:

  • .full() → CdpDocument — the full proof, the document that verifies offline. It carries the capsule's activity trail (uploaded and downloaded file names; commands only as hashes) and your metadata (not covered by the signature), as a typed object.
  • .verification() → AuditProof — the summary projection (aggregate counts, document_hash, attestation, your metadata and the capsule ID; no file names or per-step chain). It has no hash chain, so the offline verifier cannot check it; POST /v1/verify checks it with a reduced scope.
  • .toDict() → Record<string, unknown> — the full proof. Write it to a file: that file is what verify(), the nanorix-verify CLI and nanorix.io/verify accept.
  • .verifyUrl → string — the verifier page, https://nanorix.io/verify/. It does not open a proof by ID; drop the saved proof file into it.
  • .id — the capsule ID. The proof's own fields (attestation, chain and the rest) are on .full(); document_hash is on .verification().

client.auditProofs is the brand-aligned alias; both names point at the same resource and coexist forever.


client.egressProfiles

Class: EgressProfiles. Tier: Developer, Team and Enterprise: the API refuses create, update and addRule on a Free account. On a Developer account create refuses a second profile; Team and Enterprise accounts can create more. create, update, delete, addRule and removeRule are for organization admins only; list, get and listRules are open to every member. Naming a profile on capsules.create({ egressProfile }) is for Team and Enterprise accounts; the API looks the profile up by name.

client.egressProfiles.create({ name, description? })
client.egressProfiles.list()
client.egressProfiles.get(profileId)
client.egressProfiles.update(profileId, { name?, description? })
client.egressProfiles.delete(profileId)
client.egressProfiles.addRule(profileId, { domainPattern: "api.example.com", port?: 443, description? })
client.egressProfiles.listRules(profileId)
client.egressProfiles.removeRule(profileId, ruleId)

Maps to /v1/egress/profiles/....

domainPattern is an exact host name, a leading-dot wildcard (".example.com") or an IP address (a private one only where the deployment allows private destinations); port defaults to 443. For the patterns the API refuses, see the API reference for POST /v1/egress/profiles/:id/rules.


client.webhooks

Class: Webhooks.

client.webhooks.create({ url, events, description? })
client.webhooks.list()
client.webhooks.get(webhookId)
client.webhooks.update(webhookId, { url?, events?, description?, active? })
client.webhooks.delete(webhookId)
client.webhooks.test(webhookId)
client.webhooks.deliveries(webhookId)

The secret returned from create() is shown once. Use the static Webhooks.verifySignature(payload, signature, secret, timestamp) in your handler; it returns false when the signature does not match or the timestamp is more than five minutes old:

import { Webhooks } from "@nanorix/sdk";

if (!Webhooks.verifySignature(
  req.body,                                                  // raw body, Buffer or string
  req.headers["x-nanorix-signature"] as string,              // "sha256=<hex>"
  process.env.NANORIX_WEBHOOK_SECRET!,
  Number(req.headers["x-nanorix-timestamp"]),                // Unix seconds
)) {
  res.status(401).end();
  return;
}

Maps to /v1/webhooks/.... Full event-type catalog at integrations/webhooks.md.


client.usage

Class: Usage.

async summary(billingCycle?: string): Promise<UsageSummary>
async estimate(): Promise<UsageEstimate>
async listItems(opts?: ListItemsOptions): AsyncIterable<UsageItem>
async exportCsv(opts?: ListItemsOptions): Promise<Buffer>

listItems() returns an AsyncIterable paginated automatically. exportCsv() returns the raw CSV bytes — same shape as the API's /v1/usage/items.csv.

Maps to /v1/usage/....


Verifier subpackage

import {
  TrustChain,
  verifyAuditProof,
  type VerifierPolicy,
} from "@nanorix/sdk";
import * as fs from "node:fs";

// Pass the file's bytes, not JSON.parse output: a parsed object has lost the
// original bytes and the earlier copies of a repeated key, so a document the
// reference verifier refuses can verify on that route.
const bytes = fs.readFileSync("auditproof.json");

// The key list and the identity fingerprint that must have signed it. For Nanorix's own
// authority: https://verify.nanorix.io/.well-known/trust-chain.json and
// https://verify.nanorix.io/.well-known/identity.txt (confirm it through a channel you trust).
const trustChain = await TrustChain.fromKeyList(
  fs.readFileSync("trust-chain.json"),
  fs.readFileSync("identity.txt", "utf8").trim(),
);

const policy: VerifierPolicy = {
  trustChain,
  rejectDiagnostic: true,
  requiredRegion: "us-central1",
};

const result = await verifyAuditProof(bytes, policy);

// Gate on the status, never on `valid` alone: `valid` is also true at stage 7
// (not_anchored), where the signature checks only against the key the proof carries.
if (result.status !== "verified") {
  console.log("status:", result.status); // "not_anchored" or "not_verified"
  console.log("stage_reached:", result.stage_reached);
  if (result.failure_reason) console.log("failure:", result.failure_reason.type);
}

The result carries status ("verified" only at stage 8, "not_anchored" at stage 7, "not_verified" otherwise) and ok (true only when status is "verified"). valid is true when the chain and the signature hold under the key used, and on its own says nothing about who signed. It is marked @deprecated: read status or ok.

rejectDiagnostic: true refuses, at stage 2 with diagnostic_proof_refused, an AuditProof whose signed activity trail records diagnostic mode (a diagnostic_mode_enabled event), and every AuditProof whose activity is unsigned, which cannot show that the proof was not run in diagnostic mode: cdp_version 1.0, which signs only final_hash, or 2.1 or 2.2 without a signature. Only a verified result (stage 8, with trustChain) ties the trail to a key in the pinned key list; at stage 7 the key is the one the proof carries.

requiredRegion is compared with the region on the capsule_started activity event (signed on 2.1 and 2.2). Under it every AuditProof whose region is unsigned is refused at stage 2 with region_mismatch and an empty actual: cdp_version 1.0, which signs only final_hash, or 2.1 or 2.2 without a signature. Only a verified result (stage 8, with trustChain) ties the region to a key in the pinned key list.

Cross-impl byte-equivalence: verifyAuditProof() produces output byte-equivalent to the Rust nanorix-verify, Go auditproof-verifier-go, and Python SDK verify_auditproof() on the corpus wire form (valid, failure_reason, stage_reached) of the reference corpus, given the file's bytes. The FailureReason discriminated union is identical across all five paths (Rust, Go, Python, TypeScript, server-side POST /v1/verify).

The failure-reason enum is closed-set and byte-equivalent across all verifier implementations.


Compliance helpers

Framework-typed metadata builders that produce Record<string, string> payloads for the metadata argument above. Customer-declared context that is carried in the AuditProof's metadata as given; the capsule_started event (signed on 2.1 and 2.2) carries its metadata_hash; no shipped verifier compares the two.

import { HipaaContext } from "@nanorix/sdk";  // also GdprContext, Soc2Context

const metadata = new HipaaContext({
  coveredEntity: "ce-001",
  minimumNecessaryPurpose: "treatment",
  businessAssociate: "ba-002",
}).toMetadata();

const [outputs, cdp] = await client.capsules.run({
  capsulefile: "cf_...",
  inputs: { "input.pdf": pdfBytes },
  metadata,
});

The metadata is customer-defined; the compliance helpers are Nanorix-published convenience builders, not Nanorix-imposed schemas.


Request middleware

nanorixMiddleware (Express) and withNanorix / wrapApiRoute (Next.js, Node.js runtime) create one capsule for each request they wrap. The handler runs in your own process, not in the capsule. The AuditProof carries the capsule's metadata as given, and for these middleware it holds:

Key Value
sdk_wrapper_kind "middleware"
nanorix:framework the framework you gave, or the frameworkPerRoute label of the longest prefix the request path starts with
nanorix:framework_version frameworkVersion, when you pass one
sdk_agent_id agentId, when you pass one
sdk_request_method the HTTP method, in plain text
sdk_request_path by default, sha512: followed by the lowercase hex SHA-512 of the UTF-8 bytes of the request path, cut at its first ? or #. With recordRawPath: true, that cut path itself; a path over 256 bytes, or one containing ~sha512:, becomes at most its first 120 bytes plus ~sha512: and its SHA-512

The path is the one the framework gives: req.path on Express; on Next.js, nextUrl.pathname, else the pathname of req.url, else a relative req.url up to its first ? or #. Request and response bodies, the query string, the fragment, headers, status and latency do not reach the AuditProof.

import { createHash } from "node:crypto";
import { nanorixMiddleware } from "@nanorix/sdk";

app.use(nanorixMiddleware({ client, framework: "HIPAA", capsulefile: "cf_..." }));
// A request to /patients/MRN123?ssn=... puts this value under sdk_request_path:
"sha512:" + createHash("sha512").update("/patients/MRN123", "utf8").digest("hex");

// Opt in to the path itself. The query string and fragment are still cut; a
// percent-encoded ? or # is not cut, except on Flask, which decodes it,
// and on FastAPI with Starlette before 1.9.
app.use(nanorixMiddleware({ client, framework: "HIPAA", capsulefile: "cf_...", recordRawPath: true }));

The digest keeps the path out of the AuditProof, but it does not make the path secret: anyone who can list the possible paths, such as every short record number, can hash each one and find the match. Given the same path string (valid Unicode), the TypeScript and Python SDKs write byte-identical values. The frameworks hand over that string differently, though: FastAPI and Flask give the path percent-decoded, while Express and Next.js keep its percent-escapes; Express and Flask give it relative to where the app or middleware is mounted, and Next.js without its basePath and locale; and a percent-encoded ? or # is not cut, except on Flask, which decodes it, and on FastAPI with Starlette before 1.9. A path with a percent-escape, which includes every non-ASCII path, can therefore get different values from different middleware.

A request the middleware does not exclude can also write an ActivityEvent to your app's own activity file (/data/activity_events.jsonl unless NANORIX_ACTIVITY_BUFFER_PATH or NANORIX_BUFFER_PATH is set; the bufferPath option overrides both); a failed write drops it silently, and on Express a response that never finishes writes none. When the handler throws or the response has a 5xx status, the event holds the request method and path in plain text, without the query string; the error's message is added, on Express only when nanorixErrorHandler is mounted, which can write two events.


End-to-end mapping to the API surface

Every TypeScript SDK method maps to one or more API endpoints documented in api-reference.md:

TypeScript method API endpoint
client.health() GET /v1/health
client.capsulefiles.create() POST /v1/capsulefiles (+ files + finalize)
client.capsulefiles.list() GET /v1/capsulefiles
client.capsulefiles.get(id) GET /v1/capsulefiles/:id
client.capsulefiles.delete(id) DELETE /v1/capsulefiles/:id
client.capsules.create() POST /v1/capsules
LiveCapsule.upload() POST /v1/capsules/:id/upload
LiveCapsule.execute() POST /v1/capsules/:id/exec
LiveCapsule.listOutputs() GET /v1/capsules/:id/output
LiveCapsule.download() GET /v1/capsules/:id/output/:filename
LiveCapsule.destroy() DELETE /v1/capsules/:id
client.capsules.list() GET /v1/capsules
client.capsules.get(id) GET /v1/capsules/:id
client.cdp.get() / client.auditProofs.get() GET /v1/capsules/:id/cdp
client.cdp.verify() GET /v1/capsules/:id/cdp/verify
client.egressProfiles.* /v1/egress/profiles/...
client.webhooks.* /v1/webhooks/...
client.usage.* /v1/usage/...
verifyAuditProof() offline (no network)

client.capsules.run(), .batch(), and .session() are SDK-side compositions over create + upload + exec + destroy, not separate endpoints.


Browser support

The SDK is Node-first; browser bundlers (Vite, esbuild, webpack) can import it but the Node crypto builtins must be polyfilled or the verifier subpackage must be excluded. The browser-native verifier ships as a separate package (forthcoming TypeScript browser verifier).

Recommended browser pattern: keep API key on a server-side proxy, expose only verifier-relevant calls to the client.


Cross-references

Forever-Standard discipline. Every public TypeScript SDK method, every option key, every exception class, every model field is permanent. New methods / options / classes / fields are additive only. The internal-vs-external naming alias (client.cdp ↔ client.auditProofs) is structural, not transitional — both names exist forever.