@farthershore/backend exports
Every public export and declaration from @farthershore/backend.
Every public export and declaration from @farthershore/backend.
Import from @farthershore/backend. This reference is extracted from the published declaration surface for version 0.21.2. Read the collection's guides for workflows, prerequisites and failure handling.
Caches the bootstrap response and refreshes it lazily. `get()` returns the
cached value when fresh, otherwise refreshes (single-flight).
Declaration source: packages/backend/dist/types/core/bootstrap.d.ts#L25.
export declare class BootstrapClient {
private readonly runtimeToken;
private readonly endpoint;
private readonly request;
private readonly fetchImpl;
private readonly now;
private readonly minRefreshSeconds;
private readonly maxStaleMs;
private cached;
private fetchedAt;
private refreshAfterMs;
private inflight;
constructor(options: BootstrapClientOptions);
/** Cached config when fresh; otherwise refreshes. */
get(): Promise<RuntimeBootstrapResponse>;
/** Force a network refresh (single-flight). */
refresh(): Promise<RuntimeBootstrapResponse>;
/** Last cached value without triggering a refresh (null until bootstrapped). */
peek(): RuntimeBootstrapResponse | null;
/**
* Seconds since the cached response was fetched; `null` before the first
* successful bootstrap. Diagnostics only — a rejected route logs this so an
* operator can tell "cache is an hour old" from "core says it really is gone".
*/
ageSeconds(): number | null;
private isStale;
private isHardStale;
private cachedOrThrowOnHardStale;
private doBootstrap;
}
Where to reach core's bootstrap endpoint. Derived from the token's coreUrl.
Declaration source: packages/backend/dist/types/core/bootstrap.d.ts#L3.
export type BootstrapClientOptions = {
runtimeToken: string;
/** Core base URL, e.g. https://core.farthershore.com. */
coreUrl: string;
/** Optional bootstrap request metadata. */
request?: RuntimeBootstrapRequest__4b9c188578f3;
/** Injectable fetch (tests). */
fetchImpl?: typeof fetch;
/** Injectable clock in ms (tests). */
now?: () => number;
/** Minimum seconds between refreshes regardless of server hint. */
minRefreshSeconds?: number;
/**
* Maximum age for cached bootstrap authorization metadata during transient
* refresh failures. Defaults to 5 minutes.
*/
maxStaleSeconds?: number;
};
Build the byte-exact canonical signing string. This is the cross-language
gate: every SDK MUST produce identical output for identical inputs, with NO
dependence on JSON key order or Node Buffer serialization.
Declaration source: packages/backend/dist/types/runtime-signing.d.ts#L16.
declare const buildCanonicalSigningString: (input: CanonicalSigningInput) => string;
Build the fs.health() report from the current snapshot.
Declaration source: packages/backend/dist/types/core/health.d.ts#L11.
export declare function buildHealthReport(snapshot: HealthSnapshot): RuntimeHealthReport;
Normalize a query string into the canonical form: split into name=value
pairs on '&', sort by (name, then value) using byte (code-unit) order, and
re-join with '&'. Pass-through (no re-encoding) so all SDKs agree on bytes.
An empty input yields an empty string.
Declaration source: packages/backend/dist/types/runtime-signing.d.ts#L10.
declare const canonicalizeQuery: (query: string) => string;
The signed claim set. Field VALUES are language-neutral strings/integers;
the canonical serialization (in runtime-signing.ts) pins the wire bytes.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L153.
export type CanonicalSigningInput = {
/** HTTP method; canonicalized to upper-case. */
method: string;
/** Request path (no host, no query). */
path: string;
/** Raw query string (without leading '?'), or "" when absent. */
query: string;
/** Lowercase-hex SHA-256 of the raw body, EMPTY_BODY_SHA256, or "STREAM". */
bodyHash: string;
/** Gateway-minted request id (also the replay nonce). */
requestId: string;
/** Unix epoch seconds at signing time. */
timestamp: number;
businessId: string;
backendId: string;
/** Resolved route id; "" when unresolved. */
routeId: string;
policyVersion: string;
/**
* Consumer-principal wave (D3) — SHA-256 hex of the presented `X-Fs-Context`
* JWT string, or the SHA-256 of the EMPTY string when context signing is off.
* Bound into the canonical string so one request-signature verification
* covers both the request and the identity context. Compute via
* {@link hashContextToken}.
*/
contextHash: string;
};
Supervises a single `cloudflared` child process. One supervisor ⇒ one tunnel
(one backend). Restarts on unexpected exit; stays down after `shutdown()`.
Declaration source: packages/backend/dist/types/core/tunnel.d.ts#L88.
export declare class CloudflaredSupervisor {
private readonly tunnelToken;
private readonly spawn;
private readonly binaryPath;
private readonly locateBinary;
private readonly logger;
private readonly onError;
private readonly failClosed;
private readonly baseBackoffMs;
private readonly maxBackoffMs;
private readonly backoffJitter;
private readonly random;
private readonly setTimeoutFn;
private readonly clearTimeoutFn;
private readonly childEnv;
private child;
private state;
private restarts;
private consecutiveFailures;
private lastError;
private intentionalStop;
private restartTimer;
private signalsBound;
private readonly signalHandler;
constructor(options: CloudflaredSupervisorOptions);
/**
* Resolve the binary, spawn the child, wire log piping + exit handling, and
* bind SIGTERM/SIGINT. Fail-open by default (resolves; error in `status()`);
* fail-closed when configured (rejects).
*
* Async by contract: the public lifecycle API (and a future binary
* download/health-probe step) is Promise-returning even when today's body is
* synchronous, so callers can always `await fs.start()`.
*/
start(): Promise<void>;
/**
* Intentional graceful stop: cancel any pending restart, signal the child
* (SIGTERM), unbind signals, and mark the supervisor stopped. Any exit that
* the kill provokes will NOT trigger a restart. Async by lifecycle contract.
*/
shutdown(): Promise<void>;
/** Token-free status snapshot for diagnostics / health. */
status(): TunnelStatus;
/** Compact health string for `fs.health().tunnel`. */
healthString(): string;
private spawnChild;
/**
* Resolve the cloudflared binary path. Order:
* 1. an installed `@farthershore/cloudflared-<platform>` optional-dependency
* matching process.platform+arch (the injected locator), then
* 2. an explicit `binaryPath` supplied by the host, then
* 3. the bare `cloudflared` name on PATH (resolved at spawn time).
*
* On an unsupported arch (no optional dep, no binaryPath) AND no usable PATH
* fallback, this raises a clear, redacted error pointing at the sidecar — it
* NEVER downloads a binary at runtime. (Cross-platform binary management is the
* optional-dep packages' job, populated at publish time.)
*/
private resolveBinary;
/** Pipe stdout/stderr to the logger with the tunnel token redacted. */
private pipeLogs;
/**
* Build a per-stream `data` handler that BUFFERS partial lines across chunks
* before redacting. The OS can deliver a single log line in two `data` events
* with the boundary mid-token; redacting each chunk independently would let
* the two token halves slip through. Buffering until a newline reassembles
* the full line (a token never contains a newline), so redaction always sees
* the whole token. A trailing partial is held for the next chunk, or flushed
* if it grows past a safety cap (cloudflared is line-oriented, so this is a
* belt-and-suspenders guard against unbounded buffer growth).
*/
private makeLineSink;
private emitLogLine;
/** Replace every occurrence of the tunnel token with the sentinel. */
private redact;
private handleExit;
private scheduleRestart;
private backoffDelay;
private handleStartFailure;
private recordError;
private bindSignals;
private unbindSignals;
}
Public export CloudflaredSupervisorOptions.
Declaration source: packages/backend/dist/types/core/tunnel.d.ts#L32.
export type CloudflaredSupervisorOptions = {
/**
* The Cloudflare tunnel token (transport identity for `cloudflared`). HIGHLY
* sensitive: kept in memory, never logged, redacted everywhere. (Distinct from
* the runtime token / app identity.)
*/
tunnelToken: string;
/** Injected spawner (required; tests pass a fake — never a real process). */
spawn: SpawnFn;
/**
* Explicit binary path. When omitted, `locateBinary` resolves it (Linux-first
* candidates). When neither resolves, start fails with a clear error.
*/
binaryPath?: string;
/** Injected binary locator. Returns an absolute path or null if not found. */
locateBinary?: () => string | null;
/** Log sink for redacted cloudflared output. Defaults to console.error. */
logger?: (line: string) => void;
/** Error-surface callback (fail-open path). Receives a token-redacted error. */
onError?: (error: Error) => void;
/**
* When true, a spawn failure rejects `start()` (the host opted into letting a
* tunnel failure stop the app). Default false: tunnel failure ≠ app crash.
* (Request *verification* is always fail-closed regardless — different axis.)
*/
failClosed?: boolean;
/** Base backoff for the first restart (doubles each consecutive failure). */
baseBackoffMs?: number;
/** Backoff ceiling. */
maxBackoffMs?: number;
/** Jitter strategy for the restart backoff. Defaults to `equal` (the shared
* backoff default) — half the capped exponential is fixed, half randomized,
* so multiple supervisors don't re-collide in lockstep after a shared
* outage. Pass `none` for a deterministic schedule. */
backoffJitter?: JitterStrategy__d3dcffd979fd;
/** Injectable uniform random in [0, 1) for the jitter (tests pin it). Defaults
* to Math.random. */
random?: () => number;
/** Injectable timer (tests use fake timers / a custom scheduler). */
setTimeoutFn?: (cb: () => void, ms: number) => unknown;
clearTimeoutFn?: (handle: unknown) => void;
/** Process env passed to the child (tunnel token is NOT injected via env). */
childEnv?: NodeJS.ProcessEnv;
};
Compute the three response-metering headers for a payload as a plain
name→value map, attachable to ANY response mechanism (Fetch `Response`,
Express `res.set`, a raw header object). This is the metering-availability
primitive: it NEVER throws at request time — if no token is resolvable (or
signing fails) it skips stamping, reports the reason (`onSkip` / dev hook /
a `console.warn`), and returns `{}` so the builder's endpoint is never broken.
This is the framework-neutral wire recipe: `ctx.report()` is the JS surface
over it, and a Python/Go backend can stamp identical headers by building the
same payload (see `docs/response-metering-wire.md`).
Declaration source: packages/backend/dist/types/response-metering.d.ts#L83.
export declare function computeMeteringHeaders(payload: ResponseMeteringUsagePayload, options?: ComputeMeteringOptions): Promise<MeteringHeaders>;
Public export ComputeMeteringOptions.
Declaration source: packages/backend/dist/types/response-metering.d.ts#L44.
export type ComputeMeteringOptions = {
token?: string;
env?: Record<string, string | undefined>;
/** Gateway request id, for dev-mode trace/usage association (never signed). */
requestId?: string;
/**
* Called (instead of throwing) when headers cannot be stamped at request time
* — e.g. no token. The endpoint is never broken; usage is simply not metered.
*/
onSkip?: (reason: string) => void;
};
The verified consumer principal derived from the cv=2 signed context — a
tenant (`org`) plus exactly one subject. Local copy of the contracts
`ConsumerPrincipal` (the SDK never leaks `@farthershore/contracts` into a
public type signature; see runtime-signing.ts).
Declaration source: packages/backend/dist/types/core/verifyContext.d.ts#L8.
export type ConsumerPrincipal = {
org: {
id: string;
};
subject: {
kind: "member";
/** The member's stable internal id (never an IdP subject/email). */
memberId: string;
/** How this request's identity was proven. */
via: "session" | "api_key";
/** The personal `fsk_` key id when `via === "api_key"` (audit). */
keyId?: string;
} | {
kind: "service";
/** The org-owned service account id — the stable service identity. */
serviceAccountId: string;
/** The specific service `fsk_` key id (rotates; audit). */
keyId: string;
};
};
Wrap a route handler so it runs only with a GUARANTEED verified PRINCIPAL. The
strict {@link createExpressMiddleware} already attaches `req.fartherShore`
before any handler runs; this closes the type gap by handing the handler a
{@link VerifiedPrincipalContext} whose `principal` is NON-OPTIONAL (no
optional-chaining to read `ctx.principal`). It enforces that guarantee at
runtime with two fail-closed 401s BEFORE the callback runs:
- `context_unverified` when there is no verified context at all (handler
mounted without the middleware);
- `principal_required` when the context is verified but identity-less (a
valid gateway request that carried no `X-Fs-Context`) — so the callback is
never invoked with an absent `ctx.principal`.
A thrown `FartherShoreError` / `FartherShorePermissionError` — e.g. from
`requireMember(ctx)` — is mapped to its typed status; any other error is
forwarded to `next` for the app's error pipeline.
Returns the wide {@link ExpressMiddleware} so it drops straight into
`app.post(path, fs.handler(...))`: a handler whose `req` is narrowed to a
`{ fartherShore: ... }` request type is a SUBTYPE of Express's `Request` and
would fail Express's `RequestHandler` assignability — moving the verified
context onto its own `ctx` argument (not the `req` type) is what keeps the
non-optional guarantee AND Express compatibility.
Options-first overload: `fs.handler({ permission: "widgets:write" }, cb)`
asserts the verified principal holds `permission` (via the fail-closed
carrier gate — an absent permission set DENIES) BEFORE the callback runs,
responding `403 permission_denied` otherwise. The key is checked with the
unified grammar (`*` / `<subject>:*` / exact); derive route-shaped keys with
`routePermission(subject, method)`.
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L129.
export declare function createExpressHandler<Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike>(handler: VerifiedExpressHandler<Req, Res>): ExpressMiddleware;
export declare function createExpressHandler<Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike>(options: HandlerOptions, handler: VerifiedExpressHandler<Req, Res>): ExpressMiddleware;
Build the Express middleware. Captures raw body bytes, calls verifyRequest,
and fail-closes on any error.
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L105.
export declare function createExpressMiddleware(fs: FartherShore, options?: MiddlewareOptions): ExpressMiddleware;
The credential SURFACE behind a verified request, DERIVED from the signed
principal (route-surfaces wave) — no new claim, no spoofable header. A member
subject carries `via`; a service subject is always key-borne. Returns
`undefined` when the request carried no verified principal (identity-less), so
a caller can distinguish "not a portal session" from "unknown".
- `"portal_session"` ⟺ a member via a browser session (`fsc_`).
- `"api_key"` ⟺ a member's personal key OR any service key (`fsk_`).
Declaration source: packages/backend/dist/types/core/subject.d.ts#L36.
export declare function credentialKind(ctx: PrincipalCarrier): "portal_session" | "api_key" | undefined;
Decode + shape-check a cv=2 context token's PAYLOAD **without** verifying its
HS256 signature. Safe to call ONLY after the token's authenticity has been
established by another proof — in this SDK the presented `X-Fs-Context`'s
SHA-256 (`contextHash`) is bound into the Ed25519-verified request signature,
so once that request signature checks out the token bytes are byte-exact the
ones the gateway signed and its CONTENT is gateway-vouched (no HS256 secret
required). This is the DEFAULT identity path: with request signing on, a
verified request always yields the principal even when no HS256 context secret
is distributed to the backend. Returns the typed cv=2 claims, or `null` when
the token is malformed or is not a cv=2 claim.
Declaration source: packages/backend/dist/types/core/verifyContext.d.ts#L109.
export declare function decodeContextClaims(token: string): FartherShoreSignedContext | null;
Public export DEFAULT_TOKEN_ENV.
Declaration source: packages/backend/dist/types/response-metering.d.ts#L66.
declare const DEFAULT_TOKEN_ENV: "FS_RUNTIME_TOKEN";
SHA-256 of zero bytes — the canonical empty-body hash.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L143.
declare const EMPTY_BODY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
Public export ExpressMiddleware.
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L30.
export type ExpressMiddleware = (req: ExpressRequestLike, res: ExpressResponseLike, next: ExpressNext) => void;
Public export ExpressNext.
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L29.
export type ExpressNext = (err?: unknown) => void;
Minimal Express-shaped types so we don't hard-depend on
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L5.
export type ExpressRequestLike = {
method: string;
/** Original URL incl. query, e.g. "/v1/x?a=1". */
originalUrl?: string;
url?: string;
path?: string;
headers: Record<string, string | string[] | undefined>;
/** Raw body bytes if captured by an upstream raw parser. */
rawBody?: Buffer | Uint8Array;
body?: unknown;
fartherShore?: FartherShoreRequestContext;
};
Public export ExpressResponseLike.
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L17.
export type ExpressResponseLike = {
status(code: number): ExpressResponseLike;
json(body: unknown): unknown;
setHeader(name: string, value: string): void;
/**
* Node's `ServerResponse.headersSent`. This is what makes the reporting verb's
* transport choice AUTOMATIC: while it is false the measurement rides signed
* response headers (no network call); once the response is on the wire
* `ctx.report()` transparently switches to the post-stream channel.
*/
headersSent?: boolean;
};
Public export fartherShore.
Declaration source: packages/backend/dist/types/index.d.ts#L64.
declare const fartherShore: {
/** Derive everything from FS_RUNTIME_TOKEN via bootstrap. */
initFromEnv(options?: FartherShoreInitOptions): FartherShoreInstance;
};
The runtime instance. Lazily bootstraps; holds the JWKS client, nonce cache,
metering buffer, and shutdown hooks.
Declaration source: packages/backend/dist/types/core/runtime.d.ts#L84.
export declare class FartherShore {
private readonly bootstrapClient;
private readonly fetchImpl;
private readonly verificationEnabled;
private readonly meteringEnabledOverride;
private readonly runtimeToken;
private readonly coreUrl;
private readonly instanceId?;
private readonly tunnelOptions;
/** OPTIONAL HS256 secret(s) — defense-in-depth over the cv=2 X-Fs-Context. */
private readonly contextSecrets;
private readonly nonceCache;
private readonly replayProtectionDiagnostic;
private readonly shutdownManager;
/** Bounds the on-demand bootstrap refreshes an unknown route id can trigger. */
private readonly routeRefreshLimiter;
private jwks;
private postStreamUsageClient;
private tunnel;
private bootstrapped;
constructor(options?: FartherShoreInitOptions);
/** Ensure bootstrap config is loaded; build the JWKS + metering clients. */
ensureBootstrapped(): Promise<RuntimeBootstrapResponse>;
/**
* Boot-time route reconciliation (call once, before `listen()`). Reflects the
* app's real route surface, diffs it against the declared lock from bootstrap,
* REPORTS drift to the platform, and CONFIRMS the declared `pending` routes
* this replica serves. Fail-OPEN: never throws / never blocks boot.
*
* The reflection code is dynamically imported so it stays OFF the per-request
* verification hot path (the runtime stays route-unaware there). The report is
* an OUTBOUND backend→core call (same channel as bootstrap/metering), so it
* works for every transport (direct / tunnel).
*
* Returns the reconcile result (or null if reflection is unavailable / boot
* reporting failed). v1 reflects Express; `app` omitted → no-op.
*/
ready(app?: unknown): Promise<ReconcileResult__9286f3220e09 | null>;
/** Outbound report sink for `ready()` — runtime-token-authed POSTs to core. */
private buildReportSink;
/**
* Framework-neutral verification primitive. Fail-closed: throws a typed
* FartherShoreError on any verification failure. Returns the verified context.
*/
verifyRequest(input: VerifyRequestInput, options?: VerifyRequestHostOptions__981e9466821d): Promise<FartherShoreRequestContext>;
/**
* Bind the ONE reporting verb to a verified context. Identity comes from the
* context (`signedContext.subscriptionId` + `requestId`) — never from the
* caller — so a handler cannot forget it, and a background job that is handed
* this context keeps reporting against the SAME served identity.
*/
private buildReportFn;
/** Whether verification is required (bootstrap × opt-out). */
verificationRequired(): Promise<boolean>;
/**
* Start the embedded runner. For a `tunnel` backend whose runner is
* `embedded`, this supervises `cloudflared` as a child process
* (spawned via the injected/default spawner) using the tunnel token from
* bootstrap. For every other transport (`direct`, or the `sidecar` runner)
* it is a no-op — there is no SDK-managed process to run.
*
* Fail-open by default: a tunnel that cannot start does NOT crash the host app
* (request verification stays fail-closed regardless — a different axis).
*/
start(): Promise<void>;
/**
* PRIVATE transport for the post-stream lane of `ctx.report()`. Never rejects
* — a metering hiccup must not break a builder's endpoint. This is machinery,
* not surface: the ONE public reporting verb is `ctx.report()`.
*/
private reportPostStreamUsage;
/**
* How far replay protection actually reaches — `"shared"` (enforced across
* every replica) or `"single-instance"` (this process only). Deployment
* diagnostic: log it at boot, or assert on it in a smoke test, so the mode is
* never a surprise. See {@link FartherShoreInitOptions.nonceStore}.
*/
replayProtection(): ReplayProtectionDiagnostic;
/** Current local health report. */
health(): RuntimeHealthReport;
/** Graceful shutdown: flush metering + send a stopping heartbeat. */
shutdown(): Promise<void>;
/** Register an additional shutdown hook (e.g. the cloudflared supervisor). */
onShutdown(hook: () => Promise<void> | void): void;
}
The verified Farther Shore context — the identity + reporting handle a
handler (or a background job the handler hands it to) works with. Alias of
{@link FartherShoreRequestContext}: a background job is simply given the
already-verified context, so there is no second context type to learn.
Declaration source: packages/backend/dist/types/core/verifyRequest.d.ts#L85.
export type FartherShoreContext = FartherShoreRequestContext;
A verification / runtime failure with a stable, cross-language `code` and the
fail-closed HTTP status the adapter should emit.
Optionally carries a {@link LimitDescriptor} (`limitDescriptor`) when the
failure is a plan-limit deny the backend chooses to surface itself, so SDKs
can render an upgrade affordance from a backend-minted error. This is OPT-IN
plumbing — the backend normally RELAYS the gateway's deny (which already
carries the descriptor) rather than minting its own, so the field is absent on
every verification/runtime failure. Additive; no behavior change.
Declaration source: packages/backend/dist/types/core/errors.d.ts#L33.
export declare class FartherShoreError extends Error {
readonly code: FartherShoreErrorCode;
readonly status: number;
/** Present only when this error is a self-minted plan-limit deny (rare; the
* backend usually relays the gateway's descriptor-bearing deny instead). */
readonly limitDescriptor?: LimitDescriptor;
/**
* Extra scalar fields the adapters merge into the `{ error: <code> }` response
* body. Kept to strings so the body stays a flat, machine-readable envelope —
* `route_unknown` uses it to name the `routeId` that was not served, which is
* the single fact an operator needs to tell a stale cache from a real deny.
*/
readonly details?: Readonly<Record<string, string>>;
constructor(code: FartherShoreErrorCode, message: string, status?: number, limitDescriptor?: LimitDescriptor, details?: Readonly<Record<string, string>>);
}
Every code a {@link FartherShoreError} can carry.
Declaration source: packages/backend/dist/types/core/errors.d.ts#L21.
export type FartherShoreErrorCode = RuntimeErrorCode | SdkLocalErrorCode;
Public export FartherShoreInitOptions.
Declaration source: packages/backend/dist/types/core/runtime.d.ts#L21.
export type FartherShoreInitOptions = {
/** Explicit runtime token. Defaults to process.env.FS_RUNTIME_TOKEN. */
runtimeToken?: string;
/** Core base URL. Defaults to FS_CORE_URL or https://core.farthershore.com. */
coreUrl?: string;
/** Env map (tests). Defaults to process.env. */
env?: Record<string, string | undefined>;
/** Injectable fetch (tests). */
fetchImpl?: typeof fetch;
/** Optional advanced opt-outs (default: everything on). */
verification?: {
enabled?: boolean;
};
metering?: {
enabled?: boolean;
};
/** Embedded-cloudflared runner config (advanced opt-in; default DX is on). */
tunnel?: FartherShoreTunnelOptions;
/** SDK metadata forwarded to bootstrap. */
instanceId?: string;
/**
* OPTIONAL HS256 secret(s) for the gateway's cv=2 `X-Fs-Context` claim — pure
* DEFENSE-IN-DEPTH, NOT required to derive identity. The consumer principal is
* always produced from the `X-Fs-Context` token whose bytes are vouched for by
* the Ed25519 request signature (the token's SHA-256 is bound into the signed
* canonical string). These secrets add a second, independent HS256 proof: when
* configured, a presented token must ALSO pass HS256 or the request is
* rejected. They are the GATEWAY CONTEXT-SIGNING keyring values
* (`CONTEXT_SIGNING_KEYS_JSON`; supply every live key during rotation —
* try-all), NOT the business's `contextTokenSecret` (which signs `fsc_`
* INGRESS tokens verified BY the gateway — setting that here would reject every
* valid gateway request). Defaults to `FS_CONTEXT_SECRETS` (comma-separated)
* from the env. Leaving it unset is the common case.
*/
contextSecrets?: readonly string[];
/**
* OPTIONAL shared replay-prevention store. Not required: the signature's
* ~305s time window is the always-on defense, and the zero-config default is
* an in-memory per-process cache. Inject a shared atomic store (Redis /
* Memcached / Cloudflare KV / Durable Object) implementing {@link NonceStore}
* only if you want one-time-use enforced ACROSS replicas rather than within
* each one. `checkAndRemember` may be async, and should be TTL-bound to the
* signature validity window.
*
* If you do inject one, an outage of that store fails requests CLOSED — it
* never degrades to "not a replay".
*/
nonceStore?: NonceStore;
};
The conceptual public entrypoint. `fartherShore.initFromEnv()` mirrors the
language-neutral spec. The returned instance is augmented with `middleware()`
(the Express adapter) bound to itself.
Declaration source: packages/backend/dist/types/index.d.ts#L32.
export type FartherShoreInstance = FartherShore & {
/** Express middleware: strict fail-closed verify → req.fartherShore (+ strip x-fs-*). */
middleware(options?: MiddlewareOptions): ExpressMiddleware;
/**
* Wrap a route handler so it runs only with a GUARANTEED verified PRINCIPAL —
* the handler's first argument is a {@link VerifiedPrincipalContext} whose
* `principal` is NON-OPTIONAL. Fails closed (401 `context_unverified` when the
* context is absent, `principal_required` when it is identity-less) before the
* callback runs. Pairs with the strict `middleware()`.
*/
handler: {
<Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike>(handler: VerifiedExpressHandler<Req, Res>): ExpressMiddleware;
/**
* Options-first overload: `fs.handler({ permission: "widgets:write" }, cb)`
* asserts the permission (fail-closed) before the callback runs,
* responding `403 permission_denied` otherwise.
*/
<Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike>(options: HandlerOptions, handler: VerifiedExpressHandler<Req, Res>): ExpressMiddleware;
};
/**
* In-handler authorization helpers bound to the instance — the SAME shape as
* the dev runtime's `rt.authz` (which additionally traces each decision), so
* dev and prod code reads identically. Both key ONLY on `ctx.permissions`
* with FAIL-CLOSED carrier semantics: an ABSENT permission set DENIES.
*/
authz: {
/** True when the acting user holds `key` (`*` / `<subject>:*` / exact). */
hasPermission(ctx: PermissionCarrier, key: string): boolean;
/** Assert `key` is held; throws `FartherShorePermissionError` (403). */
requirePermission(ctx: PermissionCarrier, key: string): void;
};
};
Thrown by {@link requirePermission} when the acting user lacks a permission.
Distinct from {@link FartherShoreError } (which models signing/verification
failures) — authorization is a separate concern from request verification,
and its 403 status is not part of the runtime verification contract.
Declaration source: packages/backend/dist/types/core/permissions.d.ts#L8.
export declare class FartherShorePermissionError extends Error {
readonly code = "permission_denied";
readonly status = 403;
/** The permission key that was required but not held. */
readonly requiredPermission: string;
constructor(requiredPermission: string, message?: string);
}
The verified request context attached to req.fartherShore.
Declaration source: packages/backend/dist/types/core/verifyRequest.d.ts#L24.
export type FartherShoreRequestContext = {
requestId: string;
businessId: string;
backendId: string;
routeId: string;
policyVersion: string;
timestamp: number;
bodyHash: string;
/** Filled by the host bootstrap layer (tenant/customer), not by verify. */
tenantId?: string;
customerId?: string;
meters?: string[];
features?: Record<string, unknown>;
/**
* The verified CONSUMER PRINCIPAL behind this request (consumer-principal
* wave, D3) — derived from the cv=2 `X-Fs-Context` whose bytes are vouched for
* by the Ed25519 request signature (the token hash is bound into the canonical
* signing string). OPTIONAL on this raw `fs.middleware()` path: a valid gateway
* request MAY be identity-less (no `X-Fs-Context` — the gateway signs an
* empty context hash), in which case there is no principal to resolve. This
* field is typed honestly here; the `fs.handler()` path (createExpressHandler)
* is where the GUARANTEED non-optional principal lives — it rejects an
* identity-less request with `401 principal_required` before the callback runs.
* Use {@link requireMember} to narrow to the member arm on member-only routes.
*/
principal?: ConsumerPrincipal;
/**
* Managed-RBAC permissions the gateway resolved for the acting subject —
* sourced ONLY from the VERIFIED signed `X-Fs-Context` claim (the unsigned
* `x-fs-permissions` fallback is GONE). `undefined` when the claim was absent
* ⇒ FAR-723 carrier-level DENY; `[]` for an authenticated subject with no
* grants. Read via {@link hasPermission} / {@link requirePermission}.
*/
permissions?: string[];
/** Exact current-G product permissions default-allowed for this request. */
unassignedProductPermissions?: string[];
/** The VERIFIED signed cv=2 context payload. Its permissions/roles populated
* the fields above; its claims derived {@link principal}. */
signedContext?: FartherShoreSignedContext;
/** Managed-RBAC role keys the acting subject holds (display/audit only). */
roles?: string[];
/**
* THE reporting verb. `report({ meter, values, dims?, quote? })` reports
* MEASUREMENTS against the served identity this context already carries —
* there is no subscription/release argument to forget. The SDK picks the
* transport (signed in-band headers before the response is sent, the attested
* post-stream channel after it, or from a background job), so the builder
* never chooses one.
*
* Attached by the runtime facade. A context produced by the BARE
* `verifyRequest()` primitive has no metering channel, so its `report()`
* throws an error naming the fix rather than dropping the measurement.
*/
report: ReportFn__89e79b33cabf;
};
The cv=2 signed-context payload the gateway stamps into `X-Fs-Context`. Local
copy of the contracts `ConsumerContextClaims`. Identity rides the RFC 9068 /
RFC 8693 claims (`sub`, `client_id`, `act`, `subjectKind`).
Declaration source: packages/backend/dist/types/core/verifyContext.d.ts#L33.
export type FartherShoreSignedContext = {
/** Claim-format version. This SDK understands ONLY cv=2 (consumer principal). */
cv: 2;
/** Resource owner: member id (member) or service account id (service). */
sub: string;
/** API key / service credential id, when the call is key-borne. */
client_id?: string;
/** Nested actor (on-behalf-of): personal-key traffic sets `{ sub: keyId }`. */
act?: {
sub: string;
};
/** The org (tenant) id. */
org: string;
businessId: string;
compiledPlanId: string;
subscriptionId: string;
subscriberId: string;
environmentId: string | null;
subjectKey: string;
/** Which subject arm this context resolves to. */
subjectKind: "member" | "service";
/** The org-owned service account id, for service subjects (mirror of `sub`). */
serviceAccountId?: string;
/** The bound role keys (absent when unminted). */
roles?: string[];
/** The unified-authz permission claim (absent when unminted). */
permissions?: string[];
/** Exact current-G product permissions default-allowed for this request. */
unassignedProductPermissions?: string[];
};
Advanced opt-in tunnel config. The embedded runner is the default DX.
Declaration source: packages/backend/dist/types/core/runtime.d.ts#L9.
export type FartherShoreTunnelOptions = {
/** Opt out of the embedded cloudflared runner (e.g. sidecar mode). */
enabled?: boolean;
/** Injected spawner (tests/non-default hosts). Defaults to node:child_process. */
spawn?: SpawnFn;
/** Explicit cloudflared binary path. */
binaryPath?: string;
/** Crash the host app if the tunnel cannot start. Default: fail-open. */
failClosed?: boolean;
/** Log sink for redacted cloudflared output. */
logger?: (line: string) => void;
};
Public export FS_RUNTIME_TOKEN_ENV.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L118.
declare const FS_RUNTIME_TOKEN_ENV: "FS_RUNTIME_TOKEN";
Options for the `fs.handler(options, cb)` overload.
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L91.
export type HandlerOptions = {
/**
* Permission key the verified principal must hold (unified grammar:
* `*` / `<subject>:*` / exact — custom strings work). Checked with the
* FAIL-CLOSED carrier gate (`requirePermission`): an ABSENT permission set
* denies. On failure the wrapper responds `403 { error: "permission_denied" }`
* before the callback runs.
*/
permission?: string;
};
Lowercase-hex SHA-256 of the RAW request bytes. Never re-serialized JSON.
Declaration source: packages/backend/dist/types/runtime-signing.d.ts#L3.
declare const hashBody: (body: Uint8Array) => Promise<string>;
True when the acting user holds `key`. Call only with a verified request
context (the verified `X-Fs-Context` permissions claim lives on
`context.permissions`).
NOTE: this is a convenience for in-handler gating; the edge `permission`
constraint is the security boundary for route-level access.
FAIL-CLOSED: an ABSENT permission set (`ctx.permissions === undefined`)
DENIES — absence NEVER means grant-all, and the presence of a verified signed
context does NOT change that (its presence is not consulted). A DEFINED array
uses the unified {@link permissionSatisfies} rule (`*` / `<subject>:*` /
exact), so an explicit `["*"]` (org OWNER / RBAC-disabled) grants everything
and `[]` denies. A builder that wants an ungated route simply does not call
this / {@link requirePermission}.
Declaration source: packages/backend/dist/types/core/permissions.d.ts#L88.
export declare function hasPermission(ctx: PermissionCarrier, key: string): boolean;
Public export HeadersLike.
Declaration source: packages/backend/dist/types/core/verifyRequest.d.ts#L22.
export type HeadersLike = Headers | Record<string, string | string[] | undefined>;
Public export HealthSnapshot.
Declaration source: packages/backend/dist/types/core/health.d.ts#L3.
export type HealthSnapshot = {
runtimeToken: boolean;
bootstrap: boolean;
tunnel: string | null;
verification: boolean;
metering: boolean;
};
Public export HealthStatus.
Declaration source: packages/backend/dist/types/core/health.d.ts#L2.
export type HealthStatus = "starting" | "ready" | "degraded" | "stopping";
Public export HeartbeatOptions.
Declaration source: packages/backend/dist/types/core/health.d.ts#L12.
export type HeartbeatOptions = {
runtimeToken: string;
coreUrl: string;
status: HealthStatus;
instanceId?: string;
fetchImpl?: typeof fetch;
};
Convenience: top-level initFromEnv mirroring fartherShore.initFromEnv().
Declaration source: packages/backend/dist/types/index.d.ts#L69.
export declare function initFromEnv(options?: FartherShoreInitOptions): FartherShoreInstance;
True when the verified request came from the managed portal UI (a member
browser session), false when it came from an API key, and `undefined` when
there is no verified principal. Convenience over {@link credentialKind} for
the common portal-vs-API branch (e.g. richer UI payloads for portal callers).
The gateway's `enforce-surface` middleware is the SECURITY boundary; this is
for in-handler ergonomics.
Declaration source: packages/backend/dist/types/core/subject.d.ts#L45.
export declare function isPortalSession(ctx: PrincipalCarrier): boolean | undefined;
Public export Jwk.
Declaration source: packages/backend/dist/types/core/jwks.d.ts#L1.
export type Jwk = JsonWebKey & {
kid?: string;
};
Caching JWKS client. Serves the last successful key set as a warm fallback
while a refresh is failing, but only until {@link JwksClientOptions.hardStaleMs};
fails closed on a cold cache and past the hard-stale ceiling.
Declaration source: packages/backend/dist/types/core/jwks.d.ts#L43.
export declare class JwksClient {
private readonly jwksUrl;
private readonly fetchImpl;
private readonly cacheTtlMs;
private readonly hardStaleMs;
private readonly negativeCacheMs;
private readonly now;
private readonly onObservation;
private keysByKid;
private fetchedAt;
private hasFetchedOnce;
private inflight;
private readonly negativeKids;
constructor(options: JwksClientOptions);
/**
* Resolve a public JWK for `kid`, fail-closed. Throws FartherShoreError with
* `jwks_unavailable` (cold cache, or a hard-stale cache whose refresh is
* failing) or `unknown_key_id`.
*/
getKey(kid: string): Promise<Jwk>;
/** Record a confirmed-missing kid, evicting the oldest if at capacity. */
private rememberMissingKid;
private ageMs;
private isStale;
private isHardStale;
/** Current freshness of the cached key set. */
private cacheState;
private observe;
/** Fail closed when the cached key set is past the hard-stale ceiling. */
private assertWithinHardStale;
/** Single-flight refresh: concurrent callers share one fetch. */
private refresh;
private doFetch;
/**
* BOUNDED stale-while-revalidate. A COLD cache fails closed. A warm cache
* inside the soft window swallows the failure and keeps serving. Past the
* hard-stale ceiling it fails closed too — availability is worth a bounded
* window of degraded trust, not an unbounded one.
*/
private handleRefreshFailure;
}
Public export JwksClientOptions.
Declaration source: packages/backend/dist/types/core/jwks.d.ts#L19.
export type JwksClientOptions = {
jwksUrl: string;
/** Injectable fetch (tests). Defaults to globalThis.fetch. */
fetchImpl?: typeof fetch;
/** How long a successful fetch stays fresh before a background refresh. */
cacheTtlMs?: number;
/**
* Hard ceiling on serving a key set whose refresh is failing. Past this age
* the client FAILS CLOSED rather than vouching for keys it can no longer
* confirm. Must be ≥ cacheTtlMs.
*/
hardStaleMs?: number;
/** How long an unknown-kid result is negatively cached (avoids hammering). */
negativeCacheMs?: number;
/** Injectable clock (tests). */
now?: () => number;
/** Freshness//staleness observations for metrics. */
onObservation?: JwksObserver__4d7082fe0d6b;
};
C-1 — the machine-readable limit descriptor on a limit-deny body. A backend
that surfaces a plan-limit deny carries this so SDKs can render an upgrade
affordance. Structurally identical to the contracts `LimitDescriptor`.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L8.
export interface LimitDescriptor {
/** Stable identifier for the limit hit — a `limitCode` VALUE
* (`quota` | `rate_limit` | `credit` | `resource:<name>`), NOT a wire code. */
limitCode: string;
/** Metered/resource dimension when known; null otherwise. */
dimension: string | null;
/** The cap the subscriber is at when known; null otherwise. */
currentCapacity: number | null;
}
Max raw-body bytes the gateway/SDK will hash before returning 413.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L148.
declare const MAX_BODY_BYTES: number;
The wire shape of one validated measurement.
Declaration source: packages/backend/dist/types/core/report.d.ts#L70.
export type Measurement = {
meter: string;
values: MeasurementValues;
dims?: MeasurementDimensions;
};
Catalog selectors the measurement was produced under, keyed by dimension.
Declaration source: packages/backend/dist/types/core/report.d.ts#L5.
export type MeasurementDimensions = Record<string, string>;
Version of the `measurements` payload lane (additive over `rawDimsUnits`).
Declaration source: packages/backend/dist/types/core/report.d.ts#L76.
declare const MEASUREMENTS_VERSION = 1;
Observed measurement values, keyed by measure key.
Declaration source: packages/backend/dist/types/core/report.d.ts#L3.
export type MeasurementValues = Record<string, number>;
The member arm of {@link ConsumerPrincipal}'s subject.
Declaration source: packages/backend/dist/types/core/subject.d.ts#L3.
export type MemberSubject = Extract<ConsumerPrincipal["subject"], {
kind: "member";
}>;
Public export METERING_PAYLOAD_HEADER.
Declaration source: packages/backend/dist/types/response-metering.d.ts#L63.
declare const METERING_PAYLOAD_HEADER: "x-fs-metering";
Public export METERING_SIGNATURE_HEADER.
Declaration source: packages/backend/dist/types/response-metering.d.ts#L64.
declare const METERING_SIGNATURE_HEADER: "x-fs-metering-sig";
Public export METERING_TOKEN_HEADER.
Declaration source: packages/backend/dist/types/response-metering.d.ts#L65.
declare const METERING_TOKEN_HEADER: "x-fs-metering-token";
Public export MeteringError.
Declaration source: packages/backend/dist/types/response-metering.d.ts#L67.
export declare class MeteringError extends Error {
readonly code: ResponseMeteringErrorCode__bb4ee7cec8df;
constructor(code: ResponseMeteringErrorCode__bb4ee7cec8df, message: string);
}
The three response-metering headers as a plain, attachable name→value map.
Declaration source: packages/backend/dist/types/response-metering.d.ts#L43.
export type MeteringHeaders = Record<string, string>;
Public export MiddlewareOptions.
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L31.
export type MiddlewareOptions = {
/**
* STRICT BY DEFAULT (`true`). Every request is verified FAIL-CLOSED and its
* inbound `x-fs-*` headers are stripped before the handler runs — the verified
* `req.fartherShore` context is the only identity source. The builder need not
* pass this: the gateway signs every request, and a missing/invalid signature
* or context is a `401`.
*
* Set `always: false` to instead DEFER to bootstrap's
* `verification.required` flag — when the backend contract does not require
* verification, the request passes through WITHOUT a context (and without
* stripping). This is an advanced escape hatch for a backend that intentionally
* consumes no identity; the secure default is strict.
*/
always?: boolean;
/**
* Called when verification REJECTS a request, with the diagnostic detail that
* is deliberately withheld from the response body.
*
* The wire response is only `{ error: <code> }` (plus the error's `details`,
* if any) — several distinct causes share one code (`route_mismatch` covers
* both a business mismatch and a backend mismatch; an unserved route id is
* the separate `route_unknown`), and the specifics must not leak to an
* unauthenticated caller. But discarding them entirely leaves the operator
* with no way to tell which cause fired, in their OWN logs, for their OWN
* server. That is what this hook restores.
*
* Defaults to a one-line `console.warn`. Pass a function to route it into a
* structured logger, or `() => {}` to silence it.
*/
onVerificationError?: (detail: {
code: string;
message: string;
status: number;
method: string;
path: string;
}) => void;
};
The default production spawner: a thin wrapper over Node's
`child_process.spawn`. Stdio is piped (so logs flow through the redactor); the
tunnel token is passed as an argv item, never via the environment. Tests
always inject their own spawner instead of this.
Declaration source: packages/backend/dist/types/core/tunnel.d.ts#L177.
export declare function nodeSpawn(): SpawnFn;
Bounded nonce cache. `checkAndRemember(id)` returns false (and records the id)
the first time it sees an id, and true (replay) on any subsequent sighting
while the id is still retained.
Declaration source: packages/backend/dist/types/core/nonceCache.d.ts#L36.
export declare class NonceCache implements NonceStore {
private readonly maxEntries;
private readonly ttlMs;
private readonly now;
private readonly seen;
constructor(options?: NonceCacheOptions);
/**
* @returns true if `id` was already seen (a REPLAY); false on first sight
* (the id is then remembered).
*/
checkAndRemember(id: string): boolean;
/** Number of retained nonces (test/observability hook). */
get size(): number;
private evictExpired;
}
Public export NonceCacheOptions.
Declaration source: packages/backend/dist/types/core/nonceCache.d.ts#L16.
export type NonceCacheOptions = {
/**
* Max distinct nonces retained. At capacity (after expired nonces are
* removed) the cache FAILS CLOSED — new nonces are rejected as replays rather
* than evicting an unexpired one. Raise this for high single-instance
* throughput, or inject a shared {@link NonceStore}.
*/
maxEntries?: number;
/** TTL after which a nonce is forgotten. Defaults to the signature validity
* window (replay window + clock skew); a nonce older than that is rejected by
* the timestamp check anyway. Must be ≥ that window. */
ttlMs?: number;
/** Injectable clock (tests). */
now?: () => number;
};
Replay-prevention store contract. `checkAndRemember(id)` returns `true` if
`id` was already seen (a REPLAY) and `false` on first sight (recording it).
The default {@link NonceCache} is IN-MEMORY and PER-PROCESS: it prevents
replay against a single instance only. A multi-replica backend where a
captured, still-valid signed request is replayed to a DIFFERENT replica needs
a SHARED store (Redis/Memcached/Cloudflare KV/Durable Object) — inject one via
`FartherShoreInitOptions.nonceStore`. `checkAndRemember` may be async so a
network-backed store can be awaited. (Time-bounding still caps the exposure
to the signature's ~300s validity window regardless of the store.)
Declaration source: packages/backend/dist/types/core/nonceCache.d.ts#L13.
export interface NonceStore {
checkAndRemember(id: string): boolean | Promise<boolean>;
}
The subset of a verified context these helpers read.
Declaration source: packages/backend/dist/types/core/permissions.d.ts#L61.
export interface PermissionCarrier {
permissions?: readonly string[];
/** Exact product permissions default-allowed by the current G+A decision. */
unassignedProductPermissions?: readonly string[];
/**
* The verified X-Fs-Context claims, when the request carried a valid token.
* NOT consulted for permission decisions — its presence NEVER grants (an
* absent `permissions` set always denies). Retained only as part of the
* verified-context shape a carrier is built from.
*/
signedContext?: FartherShoreSignedContext;
}
Whether the granted `permissions` satisfy the required `key` under the
unified grammar: `"*"` (global), `"<subject>:*"` (subject wildcard), or the
EXACT key. NO verb-class widening (class forms are expanded to concrete verbs
server-side at save time). Superset of {@link permissionGrants } — it adds the
`<subject>:*` rung. NOTE: the `granted === undefined → true` codomain here is
the PRIMITIVE's contract (kept byte-identical to contracts for parity); it is
NOT the SDK's carrier policy. Callers gate through {@link hasPermission},
which under FAR-723 DENIES an absent permission set before ever reaching this
primitive — so absence never grants at the carrier level.
FAITHFUL COPY of the canonical `permissionSatisfies` in
`@farthershore/contracts` (`authz/verbs.ts`); the published bundle is
contracts-free, so `permissions-parity.test.ts` asserts agreement over a
shared golden table (with the backend's grace rule tested separately).
Declaration source: packages/backend/dist/types/core/permissions.d.ts#L59.
export declare function permissionSatisfies(required: string, granted: readonly string[] | undefined): boolean;
Anything carrying a verified {@link ConsumerPrincipal} (the request context).
Declaration source: packages/backend/dist/types/core/subject.d.ts#L11.
export type PrincipalCarrier = {
principal?: ConsumerPrincipal;
};
Derive the {@link ConsumerPrincipal} from a verified cv=2 payload, FAIL-CLOSED.
This is a thin, contracts-free-typed re-export of the SINGLE canonical
derivation in `@farthershore/contracts` (`authz/principal.ts`). The SDK keeps
its own local {@link ConsumerPrincipal} / {@link FartherShoreSignedContext}
*types* (so the published `.d.ts` never leaks the private contracts package),
but the derivation LOGIC lives in exactly one place — no drift is possible.
Returns `null` — never a partially-populated principal — when any identity /
authz field is invalid: an empty/whitespace `sub`/`org`/`businessId`, a
missing/unknown `subjectKind`, a `service` subject with no `serviceAccountId`
or `keyId`, a delegated `member` with an empty `act.sub`, a `permissions` /
`roles` claim that is not an array of non-empty strings, or CONTRADICTORY
identity evidence (a `serviceAccountId` that disagrees with `sub`, or a
`client_id` that disagrees with `act.sub`). The caller (`verifyRequest`) treats
`null` as tamper evidence and fails closed (`context_unverified`).
- service: `serviceAccountId = serviceAccountId ?? sub` (the two must agree),
`keyId = client_id ?? act.sub ?? sub`.
- member: `memberId = sub`; `via = "api_key"` with `keyId = act.sub` when
the delegation claim is present, else `via = "session"`.
Every derived id is the TRIMMED (canonical) value.
Declaration source: packages/backend/dist/types/core/verifyContext.d.ts#L88.
export declare function principalFromContextClaims(claims: FartherShoreSignedContext): ConsumerPrincipal | null;
Authoring shape of {@link QuoteProposal}. `amountNanos` (nanodollars PER
UNIT of the entry's measure) accepts a number, bigint, or decimal integer
string; anything else is rejected.
Declaration source: packages/backend/dist/types/core/report.d.ts#L23.
export type QuoteInput = {
currency: string;
amountNanos: number | bigint | string;
};
The validated, transmitted quote — a PROPOSED rate input, never a charge.
`amountNanos` is a decimal integer string of nanodollars **per unit of the
entry's measure** (the platform's money unit is the nanodollar); core
multiplies it by the measured quantity, clamps it into the pricing policy's
declared per-unit `{min,max}`, and flags out-of-range proposals for dispute.
Never send a total.
Declaration source: packages/backend/dist/types/core/report.d.ts#L14.
export type QuoteProposal = {
currency: string;
amountNanos: string;
};
HTTP verbs that classify as `:read`. Everything else — including the
route-catalog wildcard `*` — classifies as `:write`.
FAITHFUL COPY of the canonical `READ_METHODS` in the permissions kernel
(`@farthershore/authz/grammar/route`, re-exported by
`@farthershore/contracts/rbac`); the published bundle is contracts-free, so
`permissions-parity.test.ts` asserts agreement and the full corpus replay
lives in packages/authz/test-node/sdk-copy-parity.test.ts.
Declaration source: packages/backend/dist/types/core/permissions.d.ts#L25.
declare const READ_METHODS: ReadonlySet<string>;
The sentinel substituted for the tunnel token in any logged/serialized text.
Declaration source: packages/backend/dist/types/core/tunnel.d.ts#L31.
declare const REDACTED_TOKEN = "***REDACTED***";
Public export ReplayProtectionDiagnostic.
Declaration source: packages/backend/dist/types/core/replay-protection.d.ts#L4.
export type ReplayProtectionDiagnostic = {
mode: ReplayProtectionMode;
/** True when replay is enforced across every replica, not just this process. */
crossReplica: boolean;
};
How far one-time-use enforcement actually reaches.
Declaration source: packages/backend/dist/types/core/replay-protection.d.ts#L3.
export type ReplayProtectionMode = "shared" | "single-instance";
POST a heartbeat to core. Best-effort: resolves false on any failure rather
than throwing (tunnel/health failure ≠ verification — must not crash the app).
Declaration source: packages/backend/dist/types/core/health.d.ts#L23.
export declare function reportHealth(options: HeartbeatOptions): Promise<boolean>;
One measurement report. The complete argument surface of the verb.
Declaration source: packages/backend/dist/types/core/report.d.ts#L28.
export type ReportInput = {
/** Meter key as declared in the business release (plain string at the wire). */
meter: string;
/** Observed values keyed by measure key, e.g. `{ input_tokens: 1200 }`. */
values: MeasurementValues;
/** Catalog selectors, e.g. `{ model: "acme-4", cache_status: "hit" }`. */
dims?: MeasurementDimensions;
/**
* OPTIONAL money proposal for a `backendQuoted` pricing rule: a PER-UNIT
* rate in nanodollars (multiplied by the measured quantity — never a
* total). Opaque at the authoring boundary (a job result carries it through
* untyped); validated against {@link QuoteInput} here and transmitted as a
* {@link QuoteProposal}. Applies to every backend-quoted component of this
* report; ignored by rules that are not backend-quoted.
*/
quote?: unknown;
};
Delivery outcome. Validation faults THROW (a malformed report is a builder
bug worth surfacing); delivery faults resolve `ok: false` so a metering
hiccup never breaks the builder's endpoint. A served request may own only
one post-stream callback identity, so later calls fail explicitly.
Declaration source: packages/backend/dist/types/core/report.d.ts#L53.
export type ReportResult = {
ok: true;
transport: ReportTransport;
} | {
ok: false;
transport: ReportTransport;
reason: string;
/** The PLATFORM's error code, when the failure came back in a response
* body (e.g. `post_stream_request_not_found`). Absent for local faults.
* Surfaced so a builder can act on the cause without wrapping fetch. */
code?: string;
/** The platform's own error message, verbatim. */
message?: string;
/** HTTP status of the final delivery attempt, when there was one. */
status?: number;
};
Which channel actually carried the measurement.
Declaration source: packages/backend/dist/types/core/report.d.ts#L46.
export type ReportTransport = "in_band" | "post_stream";
Assert the request resolved to a MEMBER subject and return it narrowed. On a
gateway-enforced `subject: 'member'` route this never throws; call it in
handler code to read `memberId` without a manual discriminant check. Throws
`member_subject_required` when the subject is a service (or absent).
Declaration source: packages/backend/dist/types/core/subject.d.ts#L20.
export declare function requireMember(ctx: PrincipalCarrier): MemberSubject;
Assert the acting user holds `key`, throwing {@link FartherShorePermissionError}
(403) otherwise. Same trust model as {@link hasPermission}.
Declaration source: packages/backend/dist/types/core/permissions.d.ts#L93.
export declare function requirePermission(ctx: PermissionCarrier, key: string): void;
Assert the request resolved to a SERVICE subject and return it narrowed.
Throws `service_subject_required` when the subject is a member (or absent).
Declaration source: packages/backend/dist/types/core/subject.d.ts#L25.
export declare function requireService(ctx: PrincipalCarrier): ServiceSubject;
The signed response-metering payload. `computeMeteringHeaders` accepts one of
these directly, so a non-Express / non-Fetch handler (or a Python/Go backend
following the wire recipe) can stamp valid headers with no JS SDK at all.
`ctx.report()` is the JS surface that builds it.
`measurements` (with its `measurementsVersion`) is the measurement lane the
one reporting verb emits: `{ meter, values, dims }` as declared in the
business release. `rawDimsUnits` remains as the flat projection the gateway's
existing settlement lane reads.
Declaration source: packages/backend/dist/types/response-metering.d.ts#L20.
export type ResponseMeteringUsagePayload = {
method: string;
path: string;
rawDimsUnits?: Record<string, number>;
/** Schema version of {@link measurements}; currently `1`. */
measurementsVersion?: number;
/** Reported measurements — the authoritative rating input. */
measurements?: {
meter: string;
values: Record<string, number>;
dims?: Record<string, string>;
}[];
/** Proposed rate input for a `backendQuoted` pricing rule (core clamps it). */
quote?: {
currency: string;
amountNanos: string;
};
measureContext?: Record<string, unknown>;
creditUnitsConsumed?: Record<string, number>;
operationKey?: string;
usagePolicyId?: string;
};
Derive the permission string a credential must hold to call a route:
`<subject>:read` for safe verbs (GET / HEAD / OPTIONS, any casing),
`<subject>:write` for every other method INCLUDING the route-catalog
wildcard `*`. Use it to build in-handler permission keys from the same
grammar the edge `permission` constraint enforces — never re-spell the
`:read`/`:write` suffix locally.
FAITHFUL COPY of the canonical `routePermission` in the permissions kernel
(`@farthershore/authz/grammar/route`, re-exported by
`@farthershore/contracts/rbac`); parity asserted as for {@link READ_METHODS}.
Declaration source: packages/backend/dist/types/core/permissions.d.ts#L42.
export declare function routePermission(subject: string, method: string): string;
Mirrors SERVICE_JWT_CLOCK_SKEW_SECONDS — the per-request signer reuses the
same Ed25519/JWKS infra so the skew allowance is kept identical.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L140.
declare const RUNTIME_CLOCK_SKEW_SECONDS = 5;
C-2 — map every canonical {@link RuntimeErrorCode} (wire snake_case value) to
the core `ErrorCode` it belongs to. Total over `RuntimeErrorCode` (the
`Record<RuntimeErrorCode, …>` type makes a missing key a compile error). A
faithful copy of contracts' `RUNTIME_ERROR_CODE_TO_ERROR_CODE`.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L111.
declare const RUNTIME_ERROR_CODE_TO_ERROR_CODE: Record<RuntimeErrorCode, RuntimeMappedErrorCode>;
Public export RUNTIME_ERROR_CODES.
Declaration source: packages/backend/dist/types/generated/runtime-contract.d.ts#L1.
declare const RUNTIME_ERROR_CODES: {
readonly missingSignature: "missing_signature";
readonly malformedSignature: "malformed_signature";
readonly unknownKeyId: "unknown_key_id";
readonly jwksUnavailable: "jwks_unavailable";
readonly badSignature: "bad_signature";
readonly bodyHashMismatch: "body_hash_mismatch";
readonly routeMismatch: "route_mismatch";
readonly clockSkew: "clock_skew";
readonly expiredSignature: "expired_signature";
readonly replayedNonce: "replayed_nonce";
readonly bodyTooLarge: "body_too_large";
readonly environmentMismatch: "environment_mismatch";
readonly missingToken: "missing_token";
readonly invalidToken: "invalid_token";
readonly contextUnverified: "context_unverified";
readonly memberSubjectRequired: "member_subject_required";
readonly serviceSubjectRequired: "service_subject_required";
readonly surfaceNotAllowed: "surface_not_allowed";
};
Public export RUNTIME_HEADER_NAMES.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L126.
declare const RUNTIME_HEADER_NAMES: {
readonly signature: "x-fs-signature";
readonly keyId: "x-fs-key-id";
readonly requestId: "x-fs-request-id";
readonly timestamp: "x-fs-timestamp";
readonly businessId: "x-fs-business-id";
readonly backendId: "x-fs-backend-id";
readonly routeId: "x-fs-route-id";
readonly policyVersion: "x-fs-policy-version";
readonly bodyHash: "x-fs-body-hash";
};
Public export RUNTIME_REPLAY_WINDOW_SECONDS.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L141.
declare const RUNTIME_REPLAY_WINDOW_SECONDS = 300;
Public export RUNTIME_TOKEN_OPERATIONS.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L124.
declare const RUNTIME_TOKEN_OPERATIONS: readonly ["gateway_verification", "metering", "health", "tunnel", "drift_report"];
Public export RUNTIME_TOKEN_PREFIXES.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L119.
declare const RUNTIME_TOKEN_PREFIXES: {
readonly live: "fsrt_live_";
readonly test: "fsrt_test_";
};
Public export RuntimeBootstrapResponse.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L228.
export type RuntimeBootstrapResponse = {
business: {
id: string;
slug: string;
};
backend: {
id: string;
slug: string;
name: string;
};
/**
* Every backend id this token may serve, across ALL of the business's
* environments — `backend.id` is always a member.
*
* One deployment holds exactly one `FS_RUNTIME_TOKEN`, so an
* environment-scoped token forced a SEPARATE deployment per environment:
* serving a preview env meant repointing (and breaking) production. A
* business-scoped token serves every environment from one deployment, and the
* SDK checks the gateway's signed backend id for MEMBERSHIP of this set
* rather than equality with a single id.
*
* Optional and additive: an older core omits it and the SDK falls back to the
* single-id equality check.
*/
backendIds?: string[];
environment: {
id: string | null;
kind: RuntimeEnvironmentKind__ac9ea026fbe7;
};
operations: RuntimeTokenOperation[];
verification: RuntimeVerificationConfig__5494b13a9008;
metering: RuntimeMeteringConfig__3d27722db6c2;
transport: RuntimeTransportConfig__7254e971c589;
routes: RuntimeRouteDescriptor__48a862559af0[];
/** Reflected route-surface lock (surfaceHash + version). Present once core
* serves it; `fs.ready()` diffs the reflected surface against it. */
lock?: RuntimeLockDescriptor__0d22ecd0bb58;
policyVersion: string;
refreshAfterSeconds: number;
};
Public export RuntimeErrorCode.
Declaration source: packages/backend/dist/types/generated/runtime-contract.d.ts#L21.
export type RuntimeErrorCode = (typeof RUNTIME_ERROR_CODES)[keyof typeof RUNTIME_ERROR_CODES];
C-2 — translate a runtime code into the canonical core `ErrorCode`. Returns
`INTERNAL_ERROR` for an unrecognized value (defensive; the map is total over
known codes). Mirrors contracts' `runtimeErrorToErrorCode`.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L117.
export declare function runtimeErrorToErrorCode(code: string): RuntimeMappedErrorCode;
Public export RuntimeHealthReport.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L306.
export type RuntimeHealthReport = {
runtimeToken: boolean;
bootstrap: boolean;
tunnel: string | null;
verification: boolean;
metering: boolean;
};
C-2 — the canonical core `ErrorCode` VALUES this backend can map a
`RuntimeErrorCode` onto (the codomain of {@link RUNTIME_ERROR_CODE_TO_ERROR_CODE}).
The full core enum lives in the shared platform contracts; the SDK only needs
the subset its bridge produces. Each is a verbatim core `ErrorCode` string —
the drift guard asserts membership in the canonical enum.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L104.
export type RuntimeMappedErrorCode = "UNAUTHORIZED" | "FORBIDDEN" | "SERVICE_UNAVAILABLE" | "VALIDATION_ERROR" | "INTERNAL_ERROR";
Public export RuntimeMeteringEvent.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L268.
export type RuntimeMeteringEvent = {
event_id: string;
business_id: string;
backend_id: string;
route_id?: string;
request_id?: string;
/** Subscription the usage belongs to (billing attribution). Optional and
* additive: legacy emitters omit it; core then falls back to resolving the
* served gateway request via `request_id`, and rows that resolve neither
* way are persisted unbilled + flagged unattributable. */
subscription_id?: string;
meter: string;
qty: number;
timestamp: string;
};
Classify a presented runtime token by prefix without trusting its body.
Returns the environment kind, or `null` when the prefix is not recognized.
Declaration source: packages/backend/dist/types/runtime-signing.d.ts#L32.
declare const runtimeTokenKind: (token: string) => RuntimeTokenKind__821c369e851d | null;
Public export RuntimeTokenOperation.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L125.
export type RuntimeTokenOperation = (typeof RUNTIME_TOKEN_OPERATIONS)[number];
Codes this SDK mints on its own, which no gateway ever puts on the wire.
They deliberately do NOT live in `RUNTIME_ERROR_CODES` (the language-neutral
gateway↔backend contract mirrored from `@farthershore/contracts/runtime` and
pinned by `runtime-contract-parity.test.ts`): that set describes the protocol
the gateway speaks, and a backend→CALLER response code is not part of it.
`route_unknown` is the honest answer to "your signature is valid, this process
simply does not serve that route id" — previously indistinguishable from an
auth failure because it shared `route_mismatch`'s 401.
Declaration source: packages/backend/dist/types/core/errors.d.ts#L15.
declare const SDK_LOCAL_ERROR_CODES: {
/** Valid signature, unknown route id even after a forced bootstrap refresh. */
readonly routeUnknown: "route_unknown";
};
Public export SdkLocalErrorCode.
Declaration source: packages/backend/dist/types/core/errors.d.ts#L19.
export type SdkLocalErrorCode = (typeof SDK_LOCAL_ERROR_CODES)[keyof typeof SDK_LOCAL_ERROR_CODES];
The service arm of {@link ConsumerPrincipal}'s subject.
Declaration source: packages/backend/dist/types/core/subject.d.ts#L7.
export type ServiceSubject = Extract<ConsumerPrincipal["subject"], {
kind: "service";
}>;
Public export ShutdownHook.
Declaration source: packages/backend/dist/types/core/shutdown.d.ts#L1.
export type ShutdownHook = () => Promise<void> | void;
LIFO registry of shutdown hooks, each isolated from sibling failures.
Declaration source: packages/backend/dist/types/core/shutdown.d.ts#L3.
export declare class ShutdownManager {
private readonly hooks;
private done;
register(hook: ShutdownHook): void;
get isShutDown(): boolean;
/** Run all hooks in reverse order, isolating failures. Idempotent. */
shutdown(): Promise<void>;
}
Sign the canonical string with an Ed25519 private JWK → base64url signature.
Declaration source: packages/backend/dist/types/runtime-signing.d.ts#L25.
declare const signCanonicalString: (canonical: string, privateJwk: JsonWebKey) => Promise<string>;
The minimal child-process surface the supervisor needs. A real
`child_process.ChildProcess` satisfies this; tests pass a fake. We deliberately
do NOT depend on the full ChildProcess type so the spawner stays injectable and
the SDK does not pull a Node-only process model into the language-neutral core.
Declaration source: packages/backend/dist/types/core/tunnel.d.ts#L11.
export interface SpawnedTunnelProcess {
readonly stdout: StdioStream__d26eea00aaf1 | null;
readonly stderr: StdioStream__d26eea00aaf1 | null;
readonly pid?: number;
/** Register the process-exit handler. */
on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown;
/** Signal the child to stop. */
kill(signal?: NodeJS.Signals | number): boolean;
}
The injected spawner port. In production this is a thin wrapper over
`child_process.spawn`; in tests it is a fake that records argv. It MUST NOT be
passed `local_target` — routing is owned by Cloudflare.
Declaration source: packages/backend/dist/types/core/tunnel.d.ts#L25.
export type SpawnFn = (command: string, args: string[], options?: {
env?: NodeJS.ProcessEnv;
}) => SpawnedTunnelProcess;
Map a runtime error code to its fail-closed HTTP status. Oversized bodies are
413; a wrong-credential-surface denial is 403 (the caller IS authenticated,
just not on a surface this route admits — mirrors the canonical
`surface_not_allowed → FORBIDDEN` mapping in contracts/error-codes.ts);
all other verification failures are 401.
Declaration source: packages/backend/dist/types/core/errors.d.ts#L55.
export declare function statusForCode(code: FartherShoreErrorCode): number;
Sentinel emitted into the canonical string when a request is body-hash
exempt (streaming). Raw-byte hashing is otherwise mandatory.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L146.
declare const STREAMING_EXEMPT_BODY_HASH = "STREAM";
Public export TransportMode.
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L181.
export type TransportMode = "direct" | "tunnel";
Supervisor lifecycle states, surfaced through `status()` / `healthString()`.
Declaration source: packages/backend/dist/types/core/tunnel.d.ts#L29.
export type TunnelState = "stopped" | "starting" | "running" | "restarting" | "error";
A read-only snapshot of the supervisor — safe to serialize (token-free).
Declaration source: packages/backend/dist/types/core/tunnel.d.ts#L77.
export type TunnelStatus = {
state: TunnelState;
pid: number | null;
restarts: number;
/** Token-redacted last error message, if any. */
lastError: string | null;
};
A route handler that runs only with a GUARANTEED verified PRINCIPAL. The first
argument is the {@link VerifiedPrincipalContext} — read `ctx.principal` and
`ctx.signedContext` (and narrow with `requireMember`/`requireService`)
without any optional-chaining.
See {@link createExpressHandler}.
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L89.
export type VerifiedExpressHandler<Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike> = (ctx: VerifiedPrincipalContext, req: Req, res: Res, next: ExpressNext) => void | Promise<void>;
A verified request context whose {@link ConsumerPrincipal} is GUARANTEED
present — the shape handed to a {@link VerifiedExpressHandler}. The raw
`FartherShoreRequestContext.principal` is optional (an identity-less gateway
request is legitimate on the `fs.middleware()` path); `fs.handler()` narrows to
this type only AFTER rejecting an absent principal with `401 principal_required`,
so the callback can read `ctx.principal` (and narrow with
`requireMember`/`requireService`) without any optional-chaining.
Declaration source: packages/backend/dist/types/adapters/express.d.ts#L78.
export type VerifiedPrincipalContext = FartherShoreRequestContext & {
principal: ConsumerPrincipal;
signedContext: FartherShoreSignedContext;
};
Verify a base64url Ed25519 signature over the canonical string.
Declaration source: packages/backend/dist/types/runtime-signing.d.ts#L27.
declare const verifyCanonicalSignature: (canonical: string, signatureB64Url: string, publicJwk: JsonWebKey) => Promise<boolean>;
Verify an `X-Fs-Context` token against one or more HS256 secrets (try-all for
keyring rotation). Returns the typed cv=2 payload on success, `null` on any
failure (malformed, wrong alg, bad signature, unparseable payload, OR a
`cv !== 2` claim-format the SDK does not understand). The caller treats a
`null` as fatal (fail-closed).
Declaration source: packages/backend/dist/types/core/verifyContext.d.ts#L96.
export declare function verifyContext(token: string, secrets: readonly string[]): Promise<FartherShoreSignedContext | null>;
Public export verifyRequest.
Declaration source: packages/backend/dist/types/core/verifyRequest.d.ts#L167.
export declare function verifyRequest(input: VerifyRequestInput, deps: VerifyRequestDeps): Promise<FartherShoreRequestContext>;
Public export VerifyRequestDeps.
Declaration source: packages/backend/dist/types/core/verifyRequest.d.ts#L86.
export type VerifyRequestDeps = {
jwks: JwksClient;
nonceCache: NonceStore;
/** Expected business id (from bootstrap). When set, must match the signed claim. */
businessId?: string;
/** Expected backend id (from bootstrap). When set, must match — unless
* `backendIds` is provided, which supersedes it with a membership check. */
backendId?: string;
/**
* Every backend id this deployment may serve (from bootstrap), across all of
* the business's environments. When provided, the signed backend id must be a
* MEMBER of this set — superseding the single-id equality check above.
*
* A process holds exactly one `FS_RUNTIME_TOKEN`, so pinning to one backend id
* forced a separate deployment per environment: serving a preview env meant
* repointing (and breaking) production. A business-scoped token serves them
* all from one deployment. Still fail-closed, still bound to this business —
* just no longer bound to a single environment.
*/
backendIds?: ReadonlySet<string>;
/**
* Set of route ids this backend serves (from bootstrap). When provided AND
* the signed route-id is non-empty, the signed route must be a member —
* otherwise `route_unknown` (403), after one forced {@link refreshRouteSet}.
*/
knownRouteIds?: ReadonlySet<string>;
clockSkewSeconds?: number;
replayWindowSeconds?: number;
/** Injectable clock (seconds since epoch). */
nowSeconds?: () => number;
/**
* OPTIONAL HS256 secret(s) for the gateway's cv=2 `X-Fs-Context` claim
* (multiple = keyring rotation, try-all). Consumer-principal wave (D3): these
* are NOT required to produce the principal. The context token's authenticity
* comes from the Ed25519 REQUEST signature — the token's SHA-256 is bound into
* the canonical signing string, so a verified request already vouches for the
* token's content. Principal derivation therefore happens whenever a token is
* presented, with or without a configured secret. When these secrets ARE
* configured they add DEFENSE-IN-DEPTH: a presented token must ALSO pass HS256
* (a second, independent proof) or the request is rejected. Leaving this empty
* is the common case (the request-signature binding is sufficient).
*/
contextSecrets?: readonly string[];
/**
* The `policyVersion` of the bootstrap that produced {@link knownRouteIds}.
* When the gateway's SIGNED policy version disagrees with it, this process is
* demonstrably behind the edge — an exact, cheap refresh trigger that does not
* wait for a route id to be missed.
*/
cachedPolicyVersion?: string;
/**
* Force ONE bootstrap refresh and return the fresh route set. Called ONLY
* after the Ed25519 signature has verified, and only through
* {@link routeRefreshLimiter}. Returning `null` (or throwing) leaves the
* cached set in force — a refresh failure must never turn a KNOWN route into
* a rejection.
*/
refreshRouteSet?: RouteSetRefresher__8966fd1442e8;
/**
* Rate limiter guarding {@link refreshRouteSet}. Omitting it admits every
* refresh, which is acceptable only in tests — the runtime facade always
* supplies one so a flood of bogus route ids cannot fan out to core.
*/
routeRefreshLimiter?: RouteRefreshGate__ebb28e3c71bf;
/** Age of the cached bootstrap in seconds (diagnostics only). */
bootstrapAgeSeconds?: () => number;
/** WARN sink for route-propagation diagnostics. Defaults to `console.warn`. */
onWarn?: (message: string) => void;
};
Per-request input. `headers` keys are matched case-insensitively.
Declaration source: packages/backend/dist/types/core/verifyRequest.d.ts#L6.
export type VerifyRequestInput = {
method: string;
/** Path only (no host, no query). */
path: string;
/** Raw query string (with or without leading '?'); "" when absent. */
query?: string;
headers: HeadersLike;
/** Raw request bytes captured pre-parser; null/undefined for empty body. */
body?: Uint8Array | null;
/**
* True when the request is body-hash-exempt (streaming). The signed hash must
* then be the STREAM sentinel and the body is not hashed (size cap still
* applies upstream).
*/
streamingExempt?: boolean;
};
These declarations explain types reachable from the public exports above. They are source evidence, not supported package imports. Suffixed names are documentation identifiers that preserve distinct lexical bindings. Standard-library and third-party types (for example Promise, React and Zod) remain external boundaries; their implementation declarations are not expanded here.
Declaration source: packages/backend/dist/types/core/backoff.d.ts#L2.
export type JitterStrategy__d3dcffd979fd =
/** No jitter — the raw capped exponential (deterministic). */
"none"
/** Equal jitter — `cap/2 + random()*cap/2` (the DEFAULT). */
| "equal"
/** Full jitter — `random()*cap` (max spread, no minimum floor). */
| "full";
Declaration source: packages/backend/dist/types/core/jwks.d.ts#L5.
export type JwksCacheState__075013cca763 = "fresh" | "soft_stale" | "hard_stale" | "cold";
Declaration source: packages/backend/dist/types/core/jwks.d.ts#L6.
export type JwksObservation__b0d7452a7cf1 = {
state: JwksCacheState__075013cca763;
/** Age of the cached key set in ms (0 when cold). */
ageMs: number;
/** The `kid` being resolved, when the observation is tied to one. */
kid?: string;
};
Declaration source: packages/backend/dist/types/core/jwks.d.ts#L18.
export type JwksObserver__4d7082fe0d6b = (observation: JwksObservation__b0d7452a7cf1) => void;
Declaration source: packages/backend/dist/types/reflect/reconcile.d.ts#L23.
export interface ReconcileResult__9286f3220e09 {
/** Reflected surface matched the declared lock. */
inSync: boolean;
/** A drift report was sent. */
reportedDrift: boolean;
/** Route ids confirmed served (pending → clearable). */
confirmedRouteIds: string[];
/** A report sink call failed (swallowed — boot never blocks on it). */
reportError?: string;
}
Declaration source: packages/backend/dist/types/core/report.d.ts#L115.
export type ReportFn__89e79b33cabf = (input: ReportInput | readonly ReportInput[]) => Promise<ReportResult>;
Declaration source: packages/backend/dist/types/response-metering.d.ts#L2.
declare const RESPONSE_METERING_ERROR_CODES__ebc2ee726659: {
readonly missingToken: "missing_token";
readonly invalidMeterKey: "invalid_meter_key";
readonly invalidMeterValue: "invalid_meter_value";
readonly invalidQuote: "invalid_quote";
};
Declaration source: packages/backend/dist/types/response-metering.d.ts#L8.
export type ResponseMeteringErrorCode__bb4ee7cec8df = (typeof RESPONSE_METERING_ERROR_CODES__ebc2ee726659)[keyof typeof RESPONSE_METERING_ERROR_CODES__ebc2ee726659];
Declaration source: packages/backend/dist/types/core/report.d.ts#L78.
export type ResponseSink__b746e2445083 = {
/** True while headers can still be stamped onto the outgoing response. */
canStampHeaders(): boolean;
/** Stamp the signed metering headers onto the outgoing response. */
stampHeaders(headers: Record<string, string>): void;
};
Declaration source: packages/backend/dist/types/core/verifyRequest.d.ts#L164.
export type RouteRefreshGate__ebb28e3c71bf = {
tryAcquire(key: string): boolean;
};
Declaration source: packages/backend/dist/types/core/verifyRequest.d.ts#L159.
export type RouteSetRefresher__8966fd1442e8 = () => Promise<{
knownRouteIds: ReadonlySet<string>;
policyVersion?: string;
} | null>;
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L183.
export type RuntimeBootstrapRequest__4b9c188578f3 = {
instanceId?: string;
sdkVersion?: string;
sdkLanguage?: string;
};
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L180.
export type RuntimeEnvironmentKind__ac9ea026fbe7 = RuntimeTokenKind__821c369e851d;
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L224.
export type RuntimeLockDescriptor__0d22ecd0bb58 = {
surfaceHash: string;
lockVersion: number;
};
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L195.
export type RuntimeMeteringConfig__3d27722db6c2 = {
enabled: boolean;
endpoint: string;
credential: string;
allowedMeters: string[];
allowedRoutes: string[];
perEventMax: number;
};
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L214.
export type RuntimeRouteDescriptor__48a862559af0 = {
id: string;
method: string;
path: string;
backendId: string;
/** Declared-but-not-yet-confirmed-served route. `fs.ready()` confirms the ones
* this replica actually serves so core can clear the flag and publish. */
pending?: boolean;
};
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L123.
export type RuntimeTokenKind__821c369e851d = keyof typeof RUNTIME_TOKEN_PREFIXES;
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L203.
export type RuntimeTransportConfig__7254e971c589 = {
mode: TransportMode;
runner: TransportRunner__21383ffda4d0 | null;
originUrl?: string;
originHostname?: string;
localTarget?: string;
cloudflared?: {
tunnelToken: string;
version: string;
};
};
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L188.
export type RuntimeVerificationConfig__5494b13a9008 = {
required: boolean;
jwksUrl: string;
clockSkewSeconds: number;
replayWindowSeconds: number;
headerNames: typeof RUNTIME_HEADER_NAMES;
};
Declaration source: packages/backend/dist/types/core/tunnel.d.ts#L4.
type StdioStream__d26eea00aaf1 = Pick<EventEmitter, "on">;
Declaration source: packages/backend/dist/types/runtime-types.d.ts#L182.
export type TransportRunner__21383ffda4d0 = "embedded" | "sidecar";
Declaration source: packages/backend/dist/types/core/runtime.d.ts#L76.
export type VerifyRequestHostOptions__981e9466821d = {
responseSink?: ResponseSink__b746e2445083;
};