@serve.zone/api

@serve.zone/api is the TypeScript client for Cloudly, the serve.zone control plane. It wraps the shared @serve.zone/interfaces contracts with a CloudlyApiClient that can authenticate, open a TypedSocket connection, receive server-pushed events, and call Cloudly management APIs from services, automation, and CLI-style tools.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Install

pnpm add @serve.zone/api

What It Provides

The package exports a browser-safe management client and an explicit Node-only runtime client:

import { CloudlyApiClient } from '@serve.zone/api';
import { CloudlyApiClient as CloudlyRuntimeApiClient } from '@serve.zone/api/runtime';

CloudlyApiClient provides:

  • A TypedSocket client connected to Cloudly.
  • A local TypedRouter for Cloudly-to-client callbacks.
  • Identity helpers for token-based machine clients and username/password admin login.
  • Domain-focused API groups for clusters, services, images, registries, versioned secrets, platform bindings, backups, settings, tasks, domains, DNS, and deployments.
  • RxJS subjects for pushed cluster config updates and server actions.

The Node-only @serve.zone/api/runtime entry adds the cluster-only secretRuntime group for recipient enrollment, registration expectations, sealed secret and Corestore credential material exchange, and deployment reporting. The browser-safe root does not resolve or expose the Interfaces runtime module.

Quick Start

import { CloudlyApiClient } from '@serve.zone/api';

const cloudly = new CloudlyApiClient({
  registerAs: 'cli',
  cloudlyUrl: 'https://cloudly.example.com:443',
});

await cloudly.start();

await cloudly.loginWithUsernameAndPassword(
  process.env.CLOUDLY_USERNAME!,
  process.env.CLOUDLY_PASSWORD!
);

const services = await cloudly.services.getServices();

for (const service of services) {
  console.log(service.id, service.data.name, service.data.imageVersion);
}

cloudlyUrl defaults to process.env.CLOUDLY_URL in Node.js and then https://cloudly.layer.io:443 when not supplied. Browser clients use the default URL unless they provide cloudlyUrl explicitly.

Authentication

Use loginWithUsernameAndPassword() for human/admin-style sessions. It talks to Cloudly's HTTP TypedRequest endpoint and stores the returned identity on the client.

const identity = await cloudly.loginWithUsernameAndPassword('admin@example.com', 'password');
console.log(identity.role);

Use getIdentityByToken() for machine clients that already have a Cloudly token or jump code. This path uses the active TypedSocket connection, so call start() first.

const identity = await cloudly.getIdentityByToken(process.env.CLOUDLY_TOKEN!, {
  tagConnection: true,
  statefullIdentity: true,
});

Most API groups use cloudly.identity automatically. Pass identities explicitly only for methods that expose an identity argument.

API Groups

The client exposes focused groups instead of one large method list:

Group Purpose
cluster Create, list, fetch, and update Cloudly clusters.
services Create, list, fetch, update, delete, and inspect service registry targets.
deployments List, create, update, restart, scale, and delete deployment records.
image Create image records, list images, and push or pull image versions.
externalRegistry Manage external container registries and verify registry access.
secrets Manage versioned service, SecretSet, platform-provider, and system secrets.
secretRuntime Operate cluster-scoped sealed secret delivery, Corestore control-credential retrieval, and credential publication through the Node-only @serve.zone/api/runtime entry.
platform Read capabilities, provider configs, desired state, and service bindings.
backup Create, list, fetch, restore, and clean up isolated backup rehearsals.
settings Read and update non-secret runtime settings and test provider connectivity.
tasks List tasks, inspect executions, trigger jobs, and cancel executions.
domains and dns Manage domain inventory, verification, DNS entries, and zones.

Example service workflow:

organizationId and serviceData are both required. The former flat service-data argument is removed without a compatibility fallback.

const service = await cloudly.services.createService({
  organizationId: 'organization-primary',
  serviceData: {
    name: 'api',
    description: 'Public API service',
    imageId: 'image-api',
    imageVersion: '1.0.0',
    environment: {
      NODE_ENV: 'production',
    },
    serviceCategory: 'workload',
    deploymentStrategy: 'limited-replicas',
    scaleFactor: 2,
    balancingStrategy: 'round-robin',
    ports: {
      web: 3000,
    },
    domains: [
      {
        name: 'api',
        protocol: 'https',
      },
    ],
    deploymentIds: [],
  },
});

const registryTarget = await service.getRegistryTarget('latest');

Example platform-binding workflow:

const capabilities = await cloudly.platform.getPlatformCapabilities();
const emailBindings = await cloudly.platform.getPlatformBindings({
  capability: 'email',
});

console.log(capabilities.capabilities, emailBindings.bindings);

Secret Management

Version 12 keeps the version 10 removal of the SecretGroup and SecretBundle APIs and exposes their legacy-free replacement as cloudly.secrets. Service.getSecretBundleAsFlatObject() remains removed; plaintext flattening has no replacement API. The client consumes Interfaces 27 while retaining the administrative secret RPC surface introduced with Interfaces 24:

  • getSecretIngressRecipient()
  • listSecrets() and getSecretMetadata()
  • createSecret(), rotateSecret(), and changeSecretLifecycle()
  • getSecretVersionPurgePreflight() and purgeSecretVersion()
  • listSecretSets(), createSecretSet(), updateSecretSet(), and changeSecretSetLifecycle()
  • getSecretSetConsumerRollout()
  • setServiceSecretSetAttachments()
  • previewServiceSecretResolution()

Each method returns the complete Interfaces response, including the applicable secret, target, SecretSet, or attachment revision fences. Requests always use the authenticated client's JWT credential without forwarding identity claims. Purge preflight accepts optional cursor and limit fields and validates the exact request and response schemas. Irreversible purge requires schemaVersion, mutationId, secretId, secretVersionId, expectedSecretRevision, expectedSecretVersionRevision, and expectedTargetSecretsRevision fences.

Use provided-bytes when the API client should seal local bytes to Cloudly's current active ingress recipient:

const valueBytes = new TextEncoder().encode(process.env.DATABASE_PASSWORD!);

try {
  const result = await cloudly.secrets.createSecret({
    mutationId: crypto.randomUUID(),
    target: {
      kind: 'service',
      serviceId: 'service-api',
    },
    key: 'DATABASE_PASSWORD',
    environment: 'production',
    name: 'Database password',
    delivery: {
      type: 'launcher-environment',
      variableName: 'DATABASE_PASSWORD',
      uid: 1000,
      gid: 1000,
      mode: 0o400,
    },
    valueInput: {
      mode: 'provided-bytes',
      bytes: valueBytes,
    },
    expectedTargetSecretsRevision: 0,
  });

  console.log(result.secret.id, result.targetSecretsRevision);
} finally {
  valueBytes.fill(0);
}

The client copies caller-provided bytes. Create validates them against the selected delivery; rotate validates the byte type and 500 KiB limit before any request. Both operations obtain a fresh active ingress recipient, seal with SmartCrypto using the exact Interfaces request context, and wipe their owned byte, key, and context copies. The client does not alter the caller's array, cache recipients, retry failed mutations, or log value material. The caller remains responsible for wiping its own byte array. Direct ingress-recipient lookups reject responses with extra fields, invalid recipient metadata, or any recipient that is not active; there is no compatibility fallback.

Use { mode: 'generated', encoding, bytes } to request bounded server-side generation. A strict existing Interfaces { mode: 'sealed', envelope } input is also accepted when the caller already owns sealing; Cloudly validates its recipient and request context. Generated and externally sealed inputs do not perform an ingress-recipient lookup.

These methods require a Cloudly release that implements the Interfaces 24 secret RPCs. Control-plane releases without those handlers reject the calls.

Cluster Secret Runtime

Coreflow-style machine clients import the Node-only runtime client and use cloudly.secretRuntime after token authentication:

import { CloudlyApiClient } from '@serve.zone/api/runtime';

The group exposes the Interfaces 27 runtime request surface:

  • getSecretRecipientEnrollmentState()
  • beginSecretRecipientEnrollment() and completeSecretRecipientEnrollment()
  • getCoreflowSecretRuntimeRegistrationExpectation()
  • getResolvedSecretMaterial()
  • getCorestoreControlCredentialMaterial()
  • publishCorestoreCredentialMaterial()
  • reportSecretDeploymentState()

Every request uses only the authenticated client's JWT credential. The client reconstructs the exact wire DTO and drops extra caller fields. Cluster scope is never accepted from method options. Runtime requests use maxRetries: 0; the client does not automatically retry enrollment or deployment-report mutations. Corestore publication likewise requires the caller to reuse its exact mutationId, grant, ingress recipient fence, and sealed envelope for an explicit retry; the client never chooses organization, cluster, or provider authority. Registration itself remains a dedicated TypedSocket tag published by Coreflow with coreflowSecretRuntimeRegistrationTagId from @serve.zone/interfaces/runtime. Registration-expectation responses must be either an exact recognized unavailable response or an exact available response containing fresh, validated version 2 target, WorkloadInit approval, and active-recipient authority. Malformed, extra-field, stale, and legacy authority is rejected.

The caller remains responsible for generating and protecting the recipient private key, opening sealed material only after Interfaces verification, and computing the canonical deployment report digest.

Isolated Restore Lifecycle

Isolated restores rehearse a backup into a server-generated, non-runnable scratch namespace. Cloudly derives the source service and cluster from the authoritative backup and generates the restore, scratch namespace, staging archive, and resource mapping identifiers. Callers cannot select a runnable target service or supply those generated identifiers.

Use a stable, unique idempotency key for one restore intent. Retrying the same create request with that key returns the original restore instead of provisioning another scratch namespace.

const { restore } = await cloudly.backup.createIsolatedRestore({
  sourceBackupId: 'backup-source',
  targetNodeName: 'node-rehearsal',
  purpose: 'quarterly recovery rehearsal',
  idempotencyKey: 'quarterly-rehearsal-2026-q3',
  ttlMs: 24 * 60 * 60 * 1000,
});

const page = await cloudly.backup.getIsolatedRestores({
  sourceBackupId: restore.sourceBackupId,
  status: 'ready',
  limit: 25,
});

const current = await cloudly.backup.getIsolatedRestoreById(restore.id);

await cloudly.backup.cleanupIsolatedRestore({
  restoreId: current.restore.id,
  reason: 'rehearsal completed',
});

if (page.nextCursor) {
  const nextPage = await cloudly.backup.getIsolatedRestores({
    cursor: page.nextCursor,
    limit: 25,
  });
  console.log(nextPage.restores.length);
}

These methods require an authenticated client identity with a JWT. The client sends only the JWT credential; Cloudly must verify it and derive actor, role, tenant, and ownership authority server-side. Cleanup is asynchronous and idempotent, so inspect the returned restore status or fetch it again until it reaches cleaned.

Server-Pushed Events

Cloudly can call back into connected clients through the client's local TypedRouter. Two callback streams are exposed as RxJS subjects:

cloudly.configUpdateSubject.subscribe((configUpdate) => {
  console.log('received cluster config update', configUpdate.configData.id);
});

cloudly.serverActionSubject.subscribe((serverAction) => {
  console.log('received server action', serverAction.actionName);
});

This is why long-running clients such as Coreflow register over TypedSocket instead of using one-off HTTP requests only.

Transport Notes

The client is WebSocket-first. Some newer management methods include HTTP TypedRequest fallback through /typedrequest, but many model methods still require an active typedsocketClient. For reliable behavior, call start() before using API groups unless the method explicitly documents HTTP-only behavior, such as loginWithUsernameAndPassword().

Development

pnpm install
pnpm run build
pnpm test

The package is authored as ESM TypeScript and built strictly with tsbuild tsfolders.

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the repository license file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

S
Description
No description provided
Readme
1.5 MiB
Languages
TypeScript 100%