# Sculkworm

Zero-dependency TypeScript client for the [sculkworm](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/sculkworm/README.md) HTTP admin API.

> [!CAUTION]
> **Server-side only.** Never bundle this package into browser code or expose your tenant bearer key from `SCULKWORM_TENANTS_FILE` to a client. Anyone with the key can list, create, update, and delete dynamic routes within your tenant's domain scope. Keep Sculkworm's admin API on a private network (loopback or internal container network) and call it exclusively from your backend.

## Install

`sculkworm` is not published on npm yet. Once published, install it with:

```sh
npm install sculkworm
```

Inside this repository's pnpm workspace, reference it directly via `"sculkworm": "workspace:*"` in your package's `package.json`, or build it from source with `pnpm --filter sculkworm build` (outputs ESM and `.d.ts` files to `crates/sculkworm/sdk/js/dist/`).

## Quick start

```ts
import { SculkwormClient, SculkwormError, isValidHost, isValidTarget } from 'sculkworm';

const client = new SculkwormClient({
  baseUrl: process.env.SCULKWORM_URL ?? 'http://sculkworm:8080',
  apiKey: process.env.SCULKWORM_API_KEY!,
  // Optional: custom fetch implementation (defaults to globalThis.fetch)
  // Optional: request timeout in milliseconds (default 10_000)
  timeoutMs: 10_000,
});

// 1. Optional liveness check (unauthenticated GET /healthz).
if (!(await client.health())) {
  throw new Error('sculkworm is not reachable');
}

// 2. Optional client-side validation helpers (the server always validates).
const host = 'survival.play.sculk.network';
const target = '10.0.0.10:25565';
if (!isValidHost(host) || !isValidTarget(target)) {
  throw new Error('Invalid host or target');
}

// 3. Create or update a dynamic route (PUT /v1/routes/{host}).
// Returns { route, created } where created is true on 201 and false on 200.
const { route, created } = await client.putRoute(host, target);
console.log(created ? 'Created' : 'Updated', route);

// 4. List all dynamic routes owned by this tenant (GET /v1/routes), sorted by host.
const routes = await client.listRoutes();

// 5. Fetch one route (GET /v1/routes/{host}). Returns null on 404.
const existing = await client.getRoute(host);

// 6. Delete a route (DELETE /v1/routes/{host}).
// Resolves on 204. A 404 throws SculkwormError with code 'not_found'.
await client.deleteRoute(host);
```

## API

### `new SculkwormClient(options)`

| Option | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `baseUrl` | `string` | yes | — | Base URL of the Sculkworm HTTP admin API (trailing slash optional) |
| `apiKey` | `string` | yes | — | Tenant bearer token from `SCULKWORM_TENANTS_FILE` |
| `fetch` | `typeof fetch` | no | `globalThis.fetch` | Custom Fetch API implementation |
| `timeoutMs` | `number` | no | `10_000` | Per-request timeout via `AbortSignal.timeout` |

### Methods

- `health(): Promise<boolean>` — Probes `GET /healthz` without authentication. Returns `true` only on HTTP `200` with `{"status": "ok"}`, `false` otherwise.
- `listRoutes(): Promise<Route[]>` — Lists all dynamic routes owned by the calling tenant (`GET /v1/routes`), sorted lexicographically by `host`. Static routes and other tenants' routes are never included.
- `getRoute(host): Promise<Route | null>` — Fetches one dynamic route (`GET /v1/routes/{host}`). Returns `null` on `404` (`not_found`).
- `putRoute(host, target): Promise<PutRouteResult>` — Creates or updates an open dynamic route (`PUT /v1/routes/{host}`). Returns `{ route, created }` where `created` is `true` on `201 Created` and `false` on `200 OK` (updated or unchanged).
- `putClosedRoute(host, authorizer): Promise<PutRouteResult>` — Creates or updates a closed dynamic route (`PUT /v1/routes/{host}` with `{"mode": "closed", "authorizer": ...}`). Returns `{ route, created }` where `created` is `true` on `201 Created` and `false` on `200 OK`.
- `deleteRoute(host): Promise<void>` — Deletes a dynamic route (`DELETE /v1/routes/{host}`). Resolves on `204 No Content`. A `404` is an error (`not_found`): the SDK has no silent-ignore flag, catch `err.code === 'not_found'` if your delete is meant to be idempotent.
- `mintAgentToken(host): Promise<MintedAgentToken>` — Mints a new agent token (`POST /v1/routes/{host}/agent-token`) for a closed route, replacing any previous token. Returns `{ id, created_at, token }`; the raw `token` is only returned once.
- `revokeAgentToken(host): Promise<void>` — Revokes the current agent token (`DELETE /v1/routes/{host}/agent-token`) for a closed route. Resolves on `204 No Content`; throws `not_found` on `404` and `route_not_closed` on `409`.

### Helpers

Convenience validators matching Sculkworm's server-side rules; `getRoute`, `putRoute`, `putClosedRoute`, `deleteRoute`, `mintAgentToken` and `revokeAgentToken` run them first and throw `SculkwormError` with `invalid_host`, `invalid_target` or `invalid_authorizer` (status `null`) without sending a request; the server stays the authority:

- `isValidHost(host: string): boolean` — Checks that `host` is non-empty UTF-8 at most 255 bytes, has no whitespace, control characters, `/`, `?`, `#`, or `*`, and is non-empty after lowercasing and stripping at most one trailing dot.
- `isValidTarget(target: string): boolean` — Checks that `target` is a valid `host:port` or `[ipv6]:port` backend address with a port in `1..=65535`.

## Error handling

API errors (`401 unauthorized`, `403 host_out_of_scope`, `409 route_is_static`, `409 route_owned_by_other`, `422 invalid_host`, `422 invalid_target`, `422 target_not_allowed`, `422 too_many_routes`, `500 persist_failed`, etc.), malformed or unexpected responses (`invalid_response`), timeouts (`timeout`), and network errors (`network_error`) throw `SculkwormError`:

```ts
try {
  await client.putRoute('survival.play.sculk.network', '10.0.0.10:25565');
} catch (err) {
  if (err instanceof SculkwormError) {
    // err.status: HTTP status code, or null for network/timeout errors
    // err.code: server error.code (e.g. 'host_out_of_scope', 'route_is_static')
    //           or 'network_error' | 'timeout' | 'invalid_response' | 'invalid_host' | 'invalid_target'
    // err.message: human-readable message (apiKey is never included in message or cause)
    if (err.code === 'route_is_static') {
      // Host is pinned in SCULKWORM_ROUTES_FILE.
    }
  }
  throw err;
}
```

See [docs/api.md](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/sculkworm/docs/api.md#error-codes) for every HTTP status and `error.code`.

## Runtime support

Built strictly on standard Web APIs (`fetch`, `AbortSignal.timeout`, `URL`, `JSON`, `TextEncoder`) with zero runtime dependencies.

- Node.js 18+ (Node.js 22.18+ can import `src/index.ts` directly via native type stripping)
- Deno
- Bun
- Cloudflare Workers

## License

[MIT](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/sculkworm/sdk/js/LICENSE)
