Writing a connector
A connector is how nexus talks to an outside service, such as an HTTP API, mail or a calendar. A connector never holds a credential and never opens its own connection. This guide covers the SDK in @nexus/connectors. Read the package README and the add-a-connector runbook beside it.
Status. No connector has talked to a real service. Nothing yet registers a connector’s tools or runs its code behind the gateway. A connector you write today passes its tests against a mock. It cannot yet be used by a running company. The last section lists what a real one still needs.
What a connector is
A connector is a set of declared operations, each a read or a write, over some backend. The manifest declares:
id(lower case, the prefix of every tool name),versionanddescription;hosts: the exact host names it may reach;idempotencyHeader,rateLimitandretry;operations: for each one, itskind,actionClass,descriptionand zodinputandoutput.
BaseConnector.call does the same steps for every connector, in this order: look the operation up, refuse a write without a valid idempotency key, validate the input, run the operation, validate the output, and return { data, taint }. You only write perform.
The credential rule
Auth is by handle only. A handle is hv-secret://<path>. It names a stored secret and is useless outside vaultd. The connector passes the handle and a scheme (bearer, header or basic) to the egress port. vaultd injects the value at the last network hop.
EgressHttp rejects Authorization, Cookie, X-Api-Key and similar headers set by a connector. Never put a credential in a query, a config file, a manifest or a test. Errors name fields, never values.
Storing the secret is not a nexus command yet. Today it is a library call from @nexus/vault, and you must restart vaultd afterwards so its scrubber learns the new value.
The network is the egress port and nothing else. Do not call fetch, import node:http or use a vendor SDK that opens its own sockets. A test scans the source for that, and the conformance kit trips on global fetch and sockets at run time.
Scopes
Keep the connector’s reach as small as the work allows.
- Hosts. List exact, lower-case host names. No scheme, port or wildcard. The base URL must be plain https and its host must be in the list. Every path is checked: no
.., no//, no query, no space. - The vault. A stored secret is bound to the hosts it may be sent to.
- The grant. The manifest declares and vaultd’s grant decides. The broker applies the grant on top of the manifest, so a connector can only narrow.
- The service. Ask the provider for the narrowest credential it offers. A read-only connector should get a read-only credential.
Read versus write
Each operation has a kind and an actionClass. The class is the most dangerous thing the operation can do.
- A read has kind
readand classread. It must be safe to repeat and change nothing. - A write has kind
writeand one of:write-external,money,trading,credential,cloud-resource,publishorirreversible. The manifest check refuses a mismatch. - A message or an invitation that reaches other people is
publish. Moving money ismoney. - A reserved class (everything above except
write-external) needs a card you approve, and a tainted run loses it. Awrite-externalcall needs a single-use receipt that vaultd mints itself under policy. - Every write needs an idempotency key of 8 to 128 characters from
A-Za-z0-9._:-. A retry reuses the key, so a write that got a lost reply is safe to retry.deriveIdempotencyKeymakes a stable key per run, call, tool and arguments.
Everything a connector returns is tainted, reads and writes alike.
A skeleton
This is the shape of the reference connector, cut down to two operations.
import { z } from "zod";
import type { EgressPort, Taint } from "@nexus/schemas";
import {
BaseConnector,
ConnectorError,
EgressHttp,
RetryPolicy,
type CallContext,
type ConnectorDeps,
type ConnectorManifest,
} from "@nexus/connectors";
const Note = z.object({ id: z.string().max(128), text: z.string().max(2000) });
const NoteId = z.object({ id: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/) });
export const manifest: ConnectorManifest = {
id: "notes",
version: "0.1.0",
description: "Read and add notes in an HTTP notes service.",
hosts: ["api.notes.example"],
idempotencyHeader: "Idempotency-Key",
rateLimit: { requests: 10, perMs: 1000 },
retry: RetryPolicy.parse({}),
operations: {
"notes.get": {
kind: "read",
actionClass: "read",
description: "Fetch one note by id.",
input: NoteId,
output: Note,
},
"notes.create": {
kind: "write",
actionClass: "write-external",
description: "Add a note. Needs an idempotency key.",
input: z.object({ text: z.string().min(1).max(2000) }),
output: Note,
},
},
};
export class NotesConnector extends BaseConnector {
private readonly http: EgressHttp;
constructor(egress: EgressPort, deps?: ConnectorDeps) {
super(manifest);
this.http = new EgressHttp({
egress,
baseUrl: "https://api.notes.example",
hosts: manifest.hosts,
auth: { handle: "hv-secret://notes/api-key", scheme: "bearer" },
retry: manifest.retry,
rateLimit: manifest.rateLimit,
idempotencyHeader: manifest.idempotencyHeader,
...(deps ? { deps } : {}),
});
}
protected async perform(
op: string,
input: unknown,
ctx: CallContext,
): Promise<{ data: unknown; taint?: Taint }> {
const call = ctx.signal ? { token: ctx.token, signal: ctx.signal } : { token: ctx.token };
switch (op) {
case "notes.get": {
const { id } = input as z.infer<typeof NoteId>;
const path = `/v1/notes/${encodeURIComponent(id)}`;
const r = await this.http.request({ method: "GET", path }, call);
return { data: r.json, taint: r.taint };
}
case "notes.create": {
const key = ctx.idempotencyKey;
const req = { method: "POST", path: "/v1/notes", body: input } as const;
const r = await this.http.request(key ? { ...req, idempotencyKey: key } : req, call);
return { data: r.json, taint: r.taint };
}
default:
throw new ConnectorError("unknown-operation");
}
}
}
Keep inputs small and bounded. Strip control and bidi characters from any text you return. Throw ConnectorError with a stable code and fixed text. Never repeat what the service said in an error.
Mocks and the conformance kit
Test against a mock, never a real account. MockSandbox is an HTTP service behind the egress port. You add routes with sandbox.route(method, path, handler). It records requests on a fake clock, accepts one credential handle, and can inject faults: error statuses, dropped connections and garbage bodies. installItemsApi is a worked example of an API with paging and idempotent writes. FakeTime is virtual time, so no test waits.
Write a harness that builds a fresh subject per case, and run the kit:
const harness: ConformanceHarness = {
name: "notes",
create(env) {
const sandbox = new MockSandbox({
host: "api.notes.example",
handle: "hv-secret://notes/api-key",
token: env.token,
time: env.time,
});
// sandbox.route("GET", "/v1/notes/:id", ...) and the rest of your mock API
return {
connector: new NotesConnector(sandbox, env.deps),
samples: { "notes.get": { id: "n1" }, "notes.create": { text: "hello" } },
effects: (op) => countWhatTheBackendDid(op),
http: sandbox,
};
},
};
for (const c of conformanceCases(harness)) it(`[${c.group}] ${c.name}`, c.run);
The core cases apply to every connector. The HTTP cases add credentials by handle, backoff, Retry-After, a retried write reusing its key, the rate limit under concurrency, and refusal of malformed or oversized answers. The kit is itself tested against twelve deliberately broken connectors, so it fails when a rule is broken.
npm run typecheck -- connectors
npx vitest run packages/connectors
npx eslint packages/connectors && npx prettier --check packages/connectors
A pass proves the SDK’s rules against your mock. It does not prove the vendor behaves like the mock. The idempotency header and Retry-After handling follow common conventions, and no real vendor was checked.
What a real connector still needs
- A service egress can carry. vaultd’s egress is HTTP only, with GET, HEAD, POST, PUT, PATCH and DELETE. IMAP and SMTP are TCP, and CalDAV needs
PROPFINDandREPORT. That is why mail and calendar are mock-backed (HV-097). A real version needs an HTTP API (Gmail, Graph or JMAP, say) or a new capability inside vaultd. - A real sandbox account and a test against it (HV-098, blocked on vendor accounts). Say in the README what was and was not run against a real service.
- Registration.
connectorCatalogEntriesandconnectorToolSpecsproduce what vaultd’s catalog and the runtime need. Nothing wires them yet, and where connector code runs is an open decision. Until a tool is registered, vaultd does not know it and treats it asirreversible, which always needs a card. Do not invent a registration path. - Receipts and cards. Every write needs a single-use receipt bound to
hashArgs(tool, args). A reserved class needs an approved card first. Your connector never mints either. The gateway does. - The send gate. A connector that can send or publish also needs the consent and send gate (HV-103) and Legal approval before real use.
- A review. If it opens a new way to reach money, credentials or publishing, add a row to the threat model and check the security invariants.
Gaps in the SDK
- Classes are per operation, not per call. An event with no attendees is still
publish. - The rate limiter is per connector instance and per process.
- There is no OAuth refresh. vaultd would have to refresh a token behind the handle.
- Paging is cursor-style only.
- The static test covers production source and the tripwire covers global
fetchand sockets. Neither coversdns,dgramor a native addon in a third-party connector. Conformance is evidence, not a sandbox.
Do not
- Open a socket, call
fetchor import an HTTP library. - Put a credential, an auth header or a token anywhere but a handle.
- Return text the service sent inside an error.
- Treat connector output as trusted or clear its taint.
- Declare a write as
readto avoid a card.