@netscript/service@0.0.10Built and signed on GitHub ActionsBuilt and signed on GitHub Actions
The service runtime for NetScript: turn an oRPC router into a running Hono service with health probes, OpenAPI, Scalar docs, request tracing, and graceful shutdown — in one call.
@netscript/service
The service runtime for NetScript: turn an oRPC router into a running Hono service with health probes, OpenAPI, Scalar docs, request tracing, and graceful shutdown — in one call.
A production service is never just its handlers. It needs CORS, request logging, an OpenAPI
document, live/ready health probes an orchestrator can poll, tracing on every request, and a
shutdown path that drains in-flight work. This package materializes all of it from the oRPC router
you already have: defineService() stands up the full runtime in one call, and createService()
composes the same stages explicitly when a service needs a bespoke stack.
defineService() requires an explicit ServiceAuthPolicy: native authentication with optional
authorization, or auth: { public: true, reason: 'Public status service' }. Missing or malformed
policies fail before configuration, database startup, or listener creation. Provider-agnostic auth
ports and factories are available through ./auth.
Why teams use it
- One-call preset —
defineService(router, options)wires CORS, logging, OpenAPI JSON, Scalar docs, RPC, service info, and health, then starts the listener and returns aRunningServicehandle withaddrand an idempotentstop(). - Fluent builder —
createService(router, config)composes the same stages step by step, thenserve()starts a listener orbuild()returns a mountable app. - Health probes —
withHealth()adds/health,/health/live, and/health/ready;healthChecks.database,.kv,.service, and.customcover common dependencies. - Graceful lifecycle —
onShutdown()registers LIFO teardown hooks;serve()drains in-flight requests, installsSIGINT/SIGTERMhandlers, and accepts an externalAbortSignal. - Explicit bind address —
serve({ hostname })anddefineService(router, { hostname })bind one interface, such as'127.0.0.1'for a loopback-only listener, on both the plain and the TLS listener; omitting it keeps the all-interfaces default. - Middleware slot and body limit —
defineService(router, { middleware, bodyLimit })installs caller middleware after CORS and logging and before auth, and an opt-in request-body limit that answers oversized bodies with a typed JSON413on both the RPC and OpenAPI projections. - One app-wide budget —
createRuntimeHost()invokes existing service, worker, queue, and database drains in deterministic phase order and returns one aggregate report. - Tracing on every request — the builder registers tracing middleware as the outermost layer on every service, so each request gets a server span with W3C propagation and the service name recorded, with no per-service wiring.
- Explicit auth policy — the preset requires native guards or a public opt-out with a reason.
./authships provider-agnostic ports plus static-credential, trusted-header, contract-policy, and scope-authorizer factories.
Architecture
flowchart LR R["oRPC router"] --> D["defineService()<br/>or createService()"] D --> M["Middleware stack<br/>tracing · CORS · logging · middleware · auth · body limit"] M --> E["Endpoints<br/>/rpc · /api · OpenAPI · Scalar docs"] M --> H["Health<br/>/health · /health/live · /health/ready"] D --> G["Graceful shutdown<br/>drain · LIFO hooks · signals"]
Install
deno add jsr:@netscript/service@<version>
Pin <version> to match your installed CLI; bare jsr:@netscript/* specifiers do not resolve on
the pre-release line. Generated NetScript service entrypoints already import the pinned entry.
Quick example
import { defineService } from '@netscript/service'; import { router } from './router.ts'; // One call materializes the Hono + oRPC runtime and starts the listener: // CORS, request logging, OpenAPI JSON, Scalar docs, RPC, service info, and health. const service = await defineService(router, { auth: { public: true, reason: 'Public example service; add guards before exposing private data' }, name: 'users', version: '1.0.0', port: 3001, openapi: { title: 'Users API', description: 'User management service' }, }); // RunningService handle: addr + idempotent graceful stop() for tests and supervisors. console.log(`listening on :${service.addr.port}`); await service.stop();
Auth policy migration (breaking in 0.0.8)
DefineServiceOptions.auth is required. Omission is a type error; JavaScript callers also receive
an actionable TypeError before builder configuration, database startup, or listener creation.
Search for defineService( in existing entrypoints and choose native guards
auth: { authn: { authenticator }, authz: { authorizer } } (authorization is optional), or record
why the entire service is deliberately public. A public reason must be nonblank and cannot be
combined with authn or authz.
For a genuinely public status service, the exact migration is:
-await defineService(router, { name: 'status' }); +await defineService(router, { + name: 'status', + auth: { public: true, reason: 'Public status service with no protected operations' }, +});
The policy and its validator are the shared ServiceAuthPolicy / assertServiceAuthPolicy contract
from @netscript/service/auth, also used by plugin services. Guarded policies preserve the existing
/api protection and anonymous /health defaults; custom protect and allowAnonymous options
keep their existing semantics. createService() remains the lower-level composition API; it
installs guards through .withAuthn() and .withAuthz().
netscript service add and auth installation share the BFF composition: browserAuthenticator
verifies remote sessions and createContractAuthorizer(router) enforces procedure-local access.
/health, /api/openapi.json, /api/docs and contract-declared public demo procedures remain
anonymous. Contract-protected procedures return 401 without a session and 403 when authorization
denies it; authorized calls succeed. Without an enabled auth plugin, generation records an explicit
public opt-out explaining how to install authentication. Authored entrypoints retain their policy;
only scaffold-owned opt-outs are reconciled by service add or plugin installation. generate aspire
leaves authored inputs unchanged. Public examples below are demonstrations; declare contract access
before using them for private operations.
Exact anonymous requests
allowAnonymous accepts exact method/path objects alongside legacy string prefixes. An exact GET
entry does not admit HEAD, descendants, encoded spellings or slash/case variants. Use six entries
to leave the native health probes public while guarding every other request:
import { createService } from '@netscript/service'; import type { AuthenticatorPort } from '@netscript/service/auth'; declare const authenticator: AuthenticatorPort; const app = createService({}, { name: 'guarded-health' }) .withAuthn({ authenticator, protect: ['/'], allowAnonymous: [ { method: 'GET', path: '/health' }, { method: 'GET', path: '/health/live' }, { method: 'GET', path: '/health/ready' }, { method: 'HEAD', path: '/health' }, { method: 'HEAD', path: '/health/live' }, { method: 'HEAD', path: '/health/ready' }, ], }) .withHealth() .route('all', '/*', (c) => c.text('guarded')) .build();
Omitted or empty allowAnonymous keeps the method-blind /health prefix default. A nonempty list
replaces that default; matched contract access declarations still take precedence. Invalid exact
entries throw TypeError when middleware is constructed, before requests or a listener. OPTIONS
is not an exact anonymous method; configure withCors() for native preflight handling.
Health is now installed during build(), after authentication and body limits.
Middleware registered with use() also runs before health, even when added after withHealth(). A custom nonempty legacy list excluding /health
previously let health GET/HEAD return 200 by registration order; a rejecting authenticator now
returns 401. Add '/health' to retain the prefix capability, or use the six exact entries above.
Omitted, empty and ['/health'] lists preserve public health. Configure health checks before
build(); health checks snapshot when installed, while readiness checks retain their live array.
CORS migration (breaking in 0.0.8)
Under withCors(), the service's native CORS decision is authoritative on every response, including
RPC/OpenAPI projections, raw routes, proxied upstreams, health and errors. All six access-control
headers are restored to the configured decision, including absence; handler, upstream and oRPC
headers are replaced. Declare exposeHeaders, allowHeaders and allowMethods on withCors().
On matched RPC procedure paths under rpcPath / rpcAliases (default /api/rpc/*), withCors()
automatically appends X-NetScript-RPC-Protocol (case-insensitively deduplicated) to explicit
allowHeaders on OPTIONS preflights while leaving explicit allowHeaders on non-RPC routes
(/raw, /health, /api/* OpenAPI, and non-RPC routes sharing the prefix) unchanged, and
createRPCHandler() adds Vary: X-NetScript-RPC-Protocol on matched RPC responses (including
426 protocol-mismatch rejections). Vary retains the union of tokens present before and after
downstream handling, deduplicated case-insensitively (* wins). Services that never call
withCors() are unchanged.
withCors() and defineService() no longer grant Access-Control-Allow-Origin: * by default. An
omitted origin reads NETSCRIPT_CORS_ORIGINS once when the builder is configured. Supply
comma-separated exact HTTP(S) origins, with no path or trailing slash:
export NETSCRIPT_CORS_ORIGINS='https://app.example,https://admin.example'
Generated CLI/Aspire helpers inject the enabled web apps' allocated endpoint origins into every
service and plugin API resource. For independently launched services, configure this variable in
each service's launch environment. An unset or blank value allows no cross-origin browser reads. The
existing createPluginService() factory delegates its config.cors to this same builder, so
omitted origins consume the workspace allowlist without separate plugin policy. enableCors: false
continues to skip plugin CORS. Explicit origins override the environment, including an empty array
to deny all cross-origin access:
import { defineService, type ServiceRouter } from '@netscript/service'; declare const router: ServiceRouter; const service = await defineService(router, { auth: { public: true, reason: 'Public example service; add guards before exposing private data' }, name: 'users', cors: { origin: ['https://app.example'] }, }); await service.stop();
Builder callers use .withCors({ origin: ['https://app.example'] }); plugin callers use
cors: { origin: ['https://app.example'] }. Options such as allowHeaders without an origin
still inherit the environment allowlist. Environment entries must be exact origins; wildcard, opaque
null, malformed URLs, and URL paths fail configuration. Reading defaults requires
--allow-env=NETSCRIPT_CORS_ORIGINS; explicit origins need no environment permission.
Public APIs can opt into .withCors({ origin: '*' }) without credentials. build() rejects
wildcard plus credentials: true, including wildcard entries in arrays. Origin resolver callbacks
remain supported; a credentialed callback returning '*' grants no ACAO header. Allowlisted origins
receive their exact ACAO; other origins receive none, so the browser refuses access to the response.
CORS is a browser response policy, not authentication or CSRF protection.
The owner-approved browser auth topology is a BFF: the Fresh app owns sign-in/callback and its first-party session cookie, and its server forwards a bearer through the SDK contribution to services. Browser-to-service credentialed CORS is not part of this topology. Generated BFF routes and a real browser session round trip are follow-up scope of #1386.
Runtime shutdown
A service started through serve() owns its installed OS signal handlers by default. After a signal
it drains requests and shutdown hooks, closes shared KV/Redis and the database clients registered by
withDatabase(), then exits explicitly: 0 clean, 1 failed, 2 timed out. Database aliases are
deduplicated by object identity. defineService() and createPluginService() inherit this behavior
from the raw builder.
drainTimeoutMs is the total shutdown budget (default 30_000 ms). Process-owned signals reserve
min(5_000, drainTimeoutMs / 5) for resource cleanup, leaving 25 seconds of work drain and five
seconds of cleanup at the defaults. cleanupTimeoutMs changes that reserved portion without
extending the total. onCleanup supplies additional resource callbacks that are attempted even if a
work-drain hook hangs. When a callback already disposes the database, set
disposeDatabaseOnSignal: false to avoid also invoking the automatic database disposer.
running.stop() and an external signal stop the listener without terminating the host or closing
process-owned shared resources. For multiple embedded runtimes, use handleSignals: false and one
host-owned signal handler, or exitOnSignal: false to retain process ownership. Register any
host-owned manual-stop teardown explicitly.
Compose every in-process runtime behind one bounded shutdown handle without replacing its own drain:
import { createRuntimeHost } from '@netscript/service'; // Your own components — the host only needs something to call. declare const service: { stop(): Promise<void> }; declare const workers: { stop(reason: string): Promise<void> }; declare const queue: { stop(): Promise<void> }; declare const database: { disconnect(): Promise<void> }; const host = createRuntimeHost({ timeoutMs: 15_000, drains: [ { id: 'api', phase: 'service', drain: () => service.stop() }, { id: 'jobs', phase: 'workers', drain: () => workers.stop('shutdown') }, { id: 'messages', phase: 'queue', drain: () => queue.stop() }, { id: 'primary-db', phase: 'database', drain: () => database.disconnect() }, ], }); const report = await host.shutdown('SIGTERM');
The host drains service → workers → queue → database, preserving registration order inside each
phase. Rejected drains are reported and do not prevent later phases. If the one shared budget
expires, the active outcome is timed-out, remaining drains are skipped, and shutdown() returns
without waiting indefinitely for the slow resource.
Reach for createService() when a service needs explicit, stage-by-stage composition. The primary
authorization pattern declares access on the contract procedure and opts the application into
enforcement with createContractAuthorizer():
import { createService } from '@netscript/service'; import { createContractAuthorizer, createStaticCredentialAuthenticator, } from '@netscript/service/auth'; import { OrdersContractV1 } from '@example/contracts'; import { router } from './router.ts'; const authenticator = createStaticCredentialAuthenticator({ credentials: { 'local-token': { subject: 'service:orders', scopes: ['orders:read'], roles: ['service'] }, }, }); // OrdersContractV1 declares procedure-local metadata such as: // .meta({ access: { // authentication: 'required', // authorization: { scopes: ['orders:read'], roles: ['service'] }, // } }) const authorizer = createContractAuthorizer(OrdersContractV1); const running = await createService(router, { name: 'orders', version: '1.0.0' }) .withRPC() .withAuthn({ authenticator }) .withAuthz({ authorizer }) .withHealth() .serve({ port: 3001 }); await running.stop();
Authentication rejection and verifier failure have different HTTP meanings. An authenticator that
returns { ok: false, reason } produces 401 UNAUTHORIZED. An authenticator that throws or rejects
produces 503 SERVICE_UNAVAILABLE with the fixed message Authentication service unavailable;
exception details are not sent to the caller. The protected handler does not run in either case.
Clients should not clear a session merely because its verifier is unavailable. Errors from
downstream handlers remain owned by the application's error handler, outside the authentication
catch boundary.
This migration is opt-in. Existing unguarded services, generated scaffolds, and services that use
createScopeAuthorizer() by itself keep their current behavior. Fail-closed contract enforcement
begins only when the application supplies the result of
createContractAuthorizer(contract, { fallback?, rawRoutes?, retiredPaths? }) to .withAuthz().
Contract metadata is authoritative. For a request that matches a contract procedure, a match-aware
fallback is consulted only when that procedure has no access metadata. If neither the metadata nor a
fallback rule matches, the request is denied even when the fallback's standalone denyByDefault
setting would otherwise allow it. A fallback can neither make a declared public procedure private
nor weaken declared scopes or roles. The builder binds one resolver to its actual REST path, RPC
path, RPC aliases, and deprecated RPC route aliases, then shares that resolver with both
authentication and authorization middleware.
createScopeAuthorizer() remains supported and is not deprecated. Use it standalone for a legacy
path-prefix policy, or pass it as the match-aware migration fallback for procedures that do not yet
declare metadata:
import { createContractAuthorizer, createScopeAuthorizer } from '@netscript/service/auth'; import type { ContractPolicyContract } from '@netscript/service/auth'; declare const OrdersContractV1: ContractPolicyContract; const legacyFallback = createScopeAuthorizer({ rules: [{ match: (request) => request.path.startsWith('/api/legacy-orders'), requireScopes: ['orders:read'], }], denyByDefault: false, }); const authorizer = createContractAuthorizer(OrdersContractV1, { fallback: legacyFallback, });
authentication: 'optional' is declared for future support, currently rejected. Construction of
createContractAuthorizer() throws
[netscript.service.contract-policy] optional authentication is unsupported: <procedure>; the error
is raised while the contract is traversed, not on the first request.
A raw route added with .route(method, path, handler) under the guarded prefix matches no
procedure, so an authenticated caller receives 404 procedure_not_found with message
authz.no-contract-procedure until it is declared. Declare it with
rawRoutes:
import { createContractAuthorizer } from '@netscript/service/auth'; import type { ContractPolicyContract } from '@netscript/service/auth'; declare const OrdersContractV1: ContractPolicyContract; const authorizer = createContractAuthorizer(OrdersContractV1, { rawRoutes: [{ path: '/api/tools/mcp', authentication: 'required' }], });
A declared raw route always requires authentication, even outside protect. It is never a public
bypass. It may add authorization: { scopes?, roles? }. Matching is exact: /api/tools/mcp does
not cover /api/tools/mcp-admin or /api/tools/mcp/nested. Construction rejects wildcard or
parameter paths, a non-'required' authentication and duplicates. .build() rejects a raw path
that overlaps the REST or RPC projection.
Unknown and retired procedures
With createContractAuthorizer(), an authenticated request under a guarded prefix that matches
no served procedure returns HTTP 404 with a stable machine-readable code. Apps can declare
removed endpoints through retiredPaths to return HTTP 410 instead:
import { createContractAuthorizer, PROCEDURE_ERROR_CODES } from '@netscript/service/auth'; import type { ContractPolicyContract } from '@netscript/service/auth'; declare const OrdersContractV1: ContractPolicyContract; const authorizer = createContractAuthorizer(OrdersContractV1, { retiredPaths: ['/api/v1/orders', '/api/rpc/v1/orders/list', '/stream'], }); const upgradeCode = PROCEDURE_ERROR_CODES.RETIRED; // 'procedure_retired'
| Authenticated request | HTTP status | JSON body |
|---|---|---|
| Unknown guarded procedure | 404 | { "error": "NOT_FOUND", "message": "authz.no-contract-procedure", "code": "procedure_not_found" } |
| Declared retired path | 410 | { "error": "GONE", "message": "authz.procedure-retired", "code": "procedure_retired" } |
| Existing procedure with insufficient permission | 403 | Existing { "error": "FORBIDDEN", "message": "authz.missing-scope:…" } shape |
Missing or invalid credentials still receive the existing 401 UNAUTHORIZED response, with no
procedure code. Availability is disclosed only after authentication. Retired declarations require
authentication even outside protect and inside allowAnonymous; they never bypass authentication.
Existing public contract procedures remain public. Existing procedures, internal audience guards
and declared raw routes take precedence over retired declarations, so retirement cannot mask a
permission check. Fallback authorizers cannot revive missing or retired procedures.
Each declaration is a canonical, case-sensitive, mounted absolute path, matched for every method. Query strings are ignored. Trailing slashes, encoded spellings, siblings and descendants do not match. Parameters, wildcards, percent encoding, dot segments, repeated separators, backslashes, whitespace, query/fragment syntax and duplicates are rejected during construction. Declare REST, RPC and alias paths separately. For a parameterized removed route, undeclared concrete paths still get 404 under guarded coverage; parameterized retirement is not supported. Undeclared paths outside protected coverage retain their existing behavior.
HTTP clients can branch on the JSON code: procedure_retired is the application's signal to
show “client too old” or request an upgrade; procedure_not_found means no procedure is served at
that guarded path. These pre-dispatch middleware errors are not contract-defined oRPC errors;
clients reading raw HTTP responses should inspect the JSON code rather than parse message.
PROCEDURE_ERROR_CODES and the ProcedureErrorCode union are exported from both the package
root and @netscript/service/auth. AuthzDecision.code carries the optional typed failure, and
ProcedurePolicyResolution.retired marks a matched retired declaration for the shared auth stages.
Overlay authorizers never set that marker and retain their existing fallback behavior.
The defineService() preset accepts the same ports through its auth option. The following legacy
path-prefix form remains valid and behavior-compatible; new services should prefer contract metadata
plus createContractAuthorizer() as shown above:
import { defineService, type ServiceRouter } from '@netscript/service'; import { createScopeAuthorizer, createTrustedHeaderAuthenticator } from '@netscript/service/auth'; declare const router: ServiceRouter; const running = await defineService(router, { name: 'orders', port: 3001, auth: { authn: { authenticator: createTrustedHeaderAuthenticator({ subjectHeader: 'x-authenticated-user', scopesHeader: 'x-authenticated-scopes', }), }, authz: { authorizer: createScopeAuthorizer({ rules: [{ match: (request) => request.path.startsWith('/api/orders'), requireScopes: ['orders:read'], }], }), }, }, }); await running.stop();
Principal and handler context
@netscript/service owns both Principal and ServiceHandlerContext<TCustom>. A principal carries
the authenticated subject, readonly scopes and roles, the authentication scheme, and a
readonly verified claims bag. ServiceHandlerContext<TCustom> combines a custom context factory's
readonly fields with optional framework-owned db, traceHeaders, and principal fields.
principal is intentionally optional because auth is configured at runtime. A handler that needs
identity narrows it before use; contract policy guarantees the runtime gate, not per-procedure
TypeScript auth typestate.
OpenAPI access projection
createOpenAPISpec() projects declared contract access without rewriting other operation fields:
| Contract declaration | OpenAPI operation |
|---|---|
authentication: 'none' |
security: [] |
authentication: 'required' |
security: [{ bearerAuth: scopes }] |
Required authorization.roles |
x-netscript-roles: roles |
authentication: 'optional' |
security: [{}, { bearerAuth: [] }] |
| No authentication declaration | No generated operation-level security field |
The generated bearerAuth component is { type: 'http', scheme: 'bearer' }. Optional remains
visible in documentation even though the first runtime adapter rejects it at construction.
API at a glance
| Entry | What it gives you |
|---|---|
. |
defineService, createService, createRuntimeHost, Principal, ServiceHandlerContext, healthChecks, HEALTH_STATUS, and handler factories (createRPCHandler, createOpenAPISpec, createScalarDocs, …) |
./auth |
createStaticCredentialAuthenticator, createTrustedHeaderAuthenticator, createContractAuthorizer, createScopeAuthorizer, and the authn/authz and contract-policy types |
The always-current symbol list is
deno doc jsr:@netscript/service@<version>.
Docs
- Services & SDK — the pillar this package implements: rickylabs.github.io/netscript/services-sdk/
- Reference: rickylabs.github.io/netscript/reference/service/
- How-to — add a service: rickylabs.github.io/netscript/how-to/add-a-service/
- API docs on JSR: jsr.io/@netscript/service/doc
Compatibility
Requires Deno 2.x — the runtime listens through Deno.serve and installs Deno.addSignalListener
handlers. Services need --allow-net (listener and health probes) and --allow-env; database and
KV health checks add the permissions of the client they probe.
License
Apache-2.0 — see LICENSE. Published to JSR with cryptographically verified provenance.
Command definitions and canonical codecs
@netscript/service/commands defines immutable commands without executing them. Their handlers
remain privately bound to the exact original definition, and copied or forged definitions are
refused. Importing, defining and encoding commands require no permissions and start no resource.
Execution delegates to the explicitly supplied store and business operations and their permissions.
import { defineCommand, jsonCodec } from '@netscript/service/commands'; import { z } from 'zod'; const updateItem = defineCommand({ name: 'items.update', definitionVersion: 1, idempotency: { scope: () => 'items', fingerprint: (input: { id: string }) => input, response: jsonCodec(z.object({ updated: z.boolean() })), }, records: { audit: 'required', outbox: 'optional' }, handle: async () => ({ updated: true }), });
Names use lowercase dot/hyphen segments, start with a letter, and contain 1–120 characters.
definitionVersion is a positive safe integer and marks replay compatibility. Change it when
identity, command meaning or response decoding changes. Changing a name or scope creates a new
receipt namespace; retain the old definition through the retry window or migrate receipt keys before
deploying that change. Required idempotency is the default; mode: 'optional' explicitly permits
commands without a key. Audit and outbox policies are required, optional or forbidden.
| Surface | Purpose |
|---|---|
CommandActor / CommandEnvelope<Input> |
Narrow durable origin, input and transport identity; expected version uses a string |
CommandDefinition / CommandDefinitionSpec |
Opaque result and definition-time handler specification |
CommandContext |
Transaction client, injected clock/IDs and synchronous audit/outbox intent recorders |
CommandFailure / CommandError |
Frozen safe failure vocabulary; serialized errors omit message, stack and cause |
CommandCodec<T> / jsonCodec(schema, limits?) |
Synchronous Standard Schema validation in both directions |
canonicalCommandJson(value, limits?) |
Deterministic RFC 8785 canonical text |
parseCanonicalCommandJson(text, limits?) |
Bounded stored-text parsing with exact canonical round-trip verification |
Actor roles, scopes and claims stay outside the durable envelope. Authentication/authorization
happen before execution. Credential scheme, correlation and trace are transport/audit data, excluded
from semantic request identity. Application/business errors retain their existing mapping. Only the
three client-actionable failures map through @netscript/contracts/commands; other failures use the
application's validation/internal/service-unavailable handling.
The internal canonical protocol is jcs-v1: ECMAScript number/string serialization, UTF-16
lexicographic property order and no Unicode normalization. The default safeguards are 64 nested
containers, 10,000 aggregate value nodes/object keys and 1 MiB of UTF-8 canonical text. Optional
depth, items and bytes limits may only tighten those ceilings. Stored text is bounded before
parsing and must reserialize exactly; duplicates, whitespace, alternative numeric spellings, escaped
equivalents and different key order are refused as corrupt/noncanonical material.
Codecs reject nonfinite numbers, lone surrogates in values or keys, sparse arrays, undefined,
functions, symbols, BigInt, Date, class instances, cycles and accessors. A jsonCodec schema must
validate synchronously: a returned Promise/thenable is refused with a synchronous-validation
configuration diagnostic. No async validation result or unvalidated schema output crosses this codec
boundary. Custom codecs must also return valid bounded I-JSON before persistence.
jsonCodec() requires synchronous validation that preserves canonical JSON identity. Neutral
transforms are accepted; coercion, field stripping and value-changing transforms are rejected,
preventing a response from changing when a stored receipt is decoded.
Command execution
Compose createCommandExecutor({ store, clock?, ids?, telemetry?, receiptClaimWaitMs?, limits? })
with a database-owned CommandStorePort<TTx>. The focused /commands export keeps the root surface
unchanged. Execution performs one local interactive transaction; it never retries its handler or
sends buffered messages. Authorize the actor before calling it and keep remote effects outside the
handler. The testing store demonstrates semantics and certifies no real provider.
import { createCommandExecutor, defineCommand, jsonCodec } from '@netscript/service/commands'; import type { CommandStorePort } from '@netscript/database/commands'; import { z } from 'zod'; type Business = { update(id: string): Promise<void> }; declare const store: CommandStorePort<Business>; const update = defineCommand<'items.update', { id: string }, { updated: boolean }, Business>({ name: 'items.update', definitionVersion: 1, idempotency: { scope: () => 'items', fingerprint: (input) => input, response: jsonCodec(z.object({ updated: z.boolean() })), }, records: { audit: 'required', outbox: 'optional' }, handle: async (ctx) => { await ctx.tx.update(ctx.envelope.input.id); ctx.audit({ action: 'updated', subject: { type: 'item', id: ctx.envelope.input.id } }); return { updated: true }; }, }); const executor = createCommandExecutor({ store }); const result = await executor.execute(update, { input: { id: 'item' }, actor: { kind: 'system', subject: 'maintenance' }, correlationId: 'update', idempotencyKey: 'fixture-key-00001', }); result.value;
The executor validates, detaches and deeply freezes bounded I-JSON input and a narrowed actor before calling scope and fingerprint once. Request SHA-256 covers command, definitionVersion, scope, selected input, actor kind/subject and expectedVersion or null. A separate SHA-256 hashes the key. Scheme, correlation, W3C context and raw key are excluded from request material. Keys are 16–256 UTF-8 bytes; scope and remaining identity/header strings are 1–256 bytes. Trace context uses W3C known-field validation, retains opaque future fields, and permits empty tracestate members. Traceparent rejects HTTP control bytes (including CR, LF, NUL and DEL), while preserving allowed HTAB, SP and opaque obs-text in unknown future fields.
Defaults are 64 audit intents, 64 delivery intents and 64 KiB aggregate canonical side-row bytes, including persisted metadata. Configuration only tightens those ceilings. Each transaction receives a finite five-second timeout and validated provider claim-wait policy. Recorders perform no IO and detach canonical JSON immediately. Required/forbidden/count/byte policy and response codec validation all precede flush. Audit, outbox and receipt completion flush in that order using one bound handle; their execution ID is the winning receipt ID. Optional unkeyed attempts still have an execution ID but skip claim/completion.
Replay rechecks hash, version, completeness, canonical text and decoding, then returns the original
correlation and performs no handler or side writes. Busy issues no later query and surfaces
in_progress only after rollback. Abort checkpoints likewise await the store's rollback result.
Application errors preserve identity; typed database CommandStoreError classifications translate
to bounded service failures without reading driver text. Successful values and optional finite
telemetry completion are reported only after commit. CommandTelemetryPort is an extension seam;
this package supplies no OpenTelemetry implementation or production fault controls.
Command store testing
@netscript/service/commands/testing exports createMemoryCommandStore() for semantic unit tests.
Each store owns its state; business writes, receipt completion, audit and outbox intents share one
commit. snapshot() returns detached frozen collections and detached timestamps.
holdBeforeCommit() exposes a one-use boundary barrier. seedReceipt() and
writeBusinessOutsideTransaction() are explicit corruption and atomicity negative controls. No
testing control belongs in a production executor constructor.
import { createMemoryCommandStore } from '@netscript/service/commands/testing'; const store = createMemoryCommandStore(); await store.transaction({ receiptClaimWaitMs: 0 }, async ({ business }) => { business.compareAndSet('version', undefined, '1'); }); const committed = store.snapshot();
No permissions are required. This fake simulates Serializable interactive transactions using the
existing sqlite provider vocabulary; it certifies no SQLite or other real provider. Receipt
contention returns immediate terminal busy (supported wait is zero). Stale drafts fail without
retry, and bounded timeout/cooperative cancellation revoke the transaction handle before failure
settles. Concurrent transactions touching disjoint rows may also conflict because the fake uses one
revision for its complete state. Native providers require their own provider conformance. See
@netscript/database/commands for the raw store contract.
createCommandFaultController() arms one-use failures at the seven command boundaries.
createTestingCommandExecutor(options, controller) runs the same executor algorithm through a
private per-instance seam; a controller binds once and keeps only its latest 128 visits. Production
createCommandExecutor(options) has no fault parameter or global hook. Precommit faults roll back
business, receipt, audit and outbox together. after_commit_before_return models a lost response:
all rows remain committed and the same-key retry replays without another handler or side record.
runCommandConformance(createFixture) accepts a fresh CommandConformanceFixture<TTx> factory. The
store and row types belong to the database package; the business handle stays generic. Supply bound
write/CAS operations, detached committed inspection, corrupt receipt seeding and an explicit
outside-write negative control. createMemoryCommandConformanceFixture() is the simulated default.
The finite matrix covers named faults, replay/mismatch, scope/name/version changes, malformed
replay, cancellation, CAS, callback re-entry, no retry, terminal busy, isolation, policies and
ordered flush. It includes concurrent replay and recovery after a rolled-back leader. Replacing the
fixture's bound write with its outside-write control must fail the same-commit assertion. Real
adapters still need provider-specific driver, lock, timeout and pooled session qualification.
import { createMemoryCommandConformanceFixture, runCommandConformance, } from '@netscript/service/commands/testing'; const report = await runCommandConformance(createMemoryCommandConformanceFixture);
assertCommandDeterminism(definition, envelope, samples) evaluates actual identity logic 2–32 times
(default four), each over equivalent detached deeply frozen input/actor material. It detects scope
or fingerprint closure changes that affect sampled identity, without executing the handler or store.
Its sampled_equivalence report is finite evidence, not a universal purity guarantee; command
authors remain responsible for excluding clocks, randomness, mutable globals and IO.
Durable command outbox relay
Import createCommandOutboxRelay and its options from @netscript/service/commands/relay. Database
owns raw persistence; service decodes bounded canonical I-JSON, validates W3C fields, resolves a
copied sink registry and supervises a bounded drain. Construction starts no timer, resource or
queue. Schedule drainOnce with your existing scheduler and await stop on shutdown.
import { createCommandOutboxRelay } from '@netscript/service/commands/relay'; import type { CommandOutboxRelayStore, CommandOutboxSink } from '@netscript/service/commands/relay'; declare const store: CommandOutboxRelayStore; declare const sink: CommandOutboxSink; const relay = createCommandOutboxRelay({ store, sinks: new Map([[sink.id, sink]]), clock: { now: () => new Date() }, ids: { next: () => crypto.randomUUID() }, batchSize: 16, concurrency: 4, leaseMs: 30000, maxAttempts: 10, maxRetryDelayMs: 60000, classify: () => 'unavailable', retryAt: (attempt, now) => new Date(now.getTime() + Math.min(1000 * attempt, 60000)), }); await relay.drainOnce(); await relay.stop();
Overlapping drains serialize under one concurrency ceiling. Stop prevents new claims, signals active publishers and waits for all active and queued drains, including publishers that ignore cancellation. Aborted claimed rows are released only through their owned token; expired ownership remains for a later claim. Caller cancellation is cooperative and passed to provider/sink operations. Finite provider timeouts and sink timeouts belong to their supplied boundaries.
A generic sink may resolve void at its documented acceptance boundary. Checked worker sinks return
only normalized { identity, acceptedAt }; service validates and snapshots both before database
settlement. Payload/trace corruption or missing sinks become misconfigured; unchecked acceptance
becomes invalid_response. The six closed failure classes are persisted without exception text.
Invalid retry policies retain terminal misconfigured state rather than losing ownership. Claim or
uncertain settlement failures surface to your scheduler; an uncertain settlement is not repaired by
releasing a possibly committed lease.
Publish always precedes settlement. A crash after acceptance and before durable publication marking redelivers the stable outbox ID/dedupe key. This is at-least-once delivery. One effective operation requires an independently idempotent downstream persistence boundary. The semantic fixture proves its own applied-key persistence explicitly; it does not certify a remote transport.
Supply optional telemetry and explicit provider for the structurally compatible C4 relay/publish
adapter. Start inputs select only command name/version, provider, isolation and finite idempotency;
raw identities, topic, payload and errors are excluded. Deferred publication restores the validated
persisted parent; the active producer context is injected for downstream consumers. Observer setup,
finish and end errors do not change the once-only operation result. Import/construction needs no
permissions; supplied provider/sinks need their consumer-owned permissions.
Command telemetry
Command execution can use createOtelCommandTelemetryPort from @netscript/telemetry/commands,
configured with the registered command definitions. Its structural port traces early rejected and
cancelled attempts as well as committed/replayed attempts. Definitions are verified before tracing;
validation and identity occur once within the observed operation. Completion observer failures do
not replace committed results. Command spans join through native span context and deliberately
exclude envelope identities, keys, hashes, payloads and correlation IDs.
Anonymous route rate limits
Use the existing middleware seam to reject requests before routing. Selected routes share a
fixed-window quota per key; the default key is the socket client address. Health routes are
installed at build(), so registered middleware runs before them. Install the limiter before
withServiceInfo() if the immediate service-info route should also be limited.
import { createService } from '@netscript/service'; import { createMemoryRateLimitStore } from '@netscript/service/rate-limit'; const app = createService({}, { name: 'device' }) .withRateLimit({ routes: ['/device/start', '/device/poll'], limit: 10, windowMs: 60_000, store: createMemoryRateLimitStore(), }) .route('post', '/device/start', (c) => c.json({ started: true })) .route('post', '/device/poll', (c) => c.json({ pending: true })) .build();
A rejected request receives JSON { error: 'RATE_LIMITED' } and Retry-After in whole seconds
rounded up from decision.retryAt ?? decision.resetAt. For shared production state, import
createKvRateLimitStore from @netscript/service/rate-limit and pass a @netscript/kv store with
atomic support and a dedicated prefix. Each request makes at most eight read/CAS attempts (sixteen
KV round trips); contention budget exhaustion rejects conservatively. Store failures propagate to
the service error handler.
Pass policy: { kind: 'gcra', burst? } to either createMemoryRateLimitStore or
createKvRateLimitStore to opt into alignment-independent rolling quotas (Generic Cell Rate
Algorithm) with an O(1) stored record per key while keeping { kind: 'fixed-window' } as the
unchanged default. burst defaults to limit. On GCRA quota exhaustion, RateLimitDecision.retryAt
reports the exact earliest representable next eligible epoch millisecond (and advisory backoff on KV
CAS contention or memory capacity saturation), so middleware emits Retry-After from retryAt
rather than waiting for full bucket recovery (resetAt).
import { getKv } from '@netscript/kv'; import { createService } from '@netscript/service'; import { createKvRateLimitStore } from '@netscript/service/rate-limit'; const kv = await getKv(); const readStore = createKvRateLimitStore(kv, { prefix: ['protected-reads-gcra', 'items'], policy: { kind: 'gcra', burst: 5 }, }); readStore.validate?.({ limit: 60, windowMs: 60_000 }); const app = createService({}, { name: 'catalog' }) .withRateLimit({ routes: ['/api/items', '/api/rpc/items/*'], limit: 60, windowMs: 60_000, store: readStore, }) .route('get', '/api/items', (c) => c.json({ items: [] })) .build(); void app;
Rolling quota sharing assumes callers sharing a store/prefix use one coherent
(limit, windowMs, burst) policy; differing tuples hit independent policy-scoped buckets. GCRA adds
a fixed 5_000 ms clock-skew retention bound (expireIn = (resetAt - now) + 5_000 in KV, matched
by rotating eviction in memory) and enforces a 365-day (31_536_000_000 ms) retention ceiling
synchronously at startup via store.validate?.({ limit, windowMs }) (invoked automatically by
createRateLimitMiddleware() / .withRateLimit() and callable directly for post-auth
store.consume() callers). Use prefixes that are disjoint after backend serialization when
migrating or changing policy (especially on Redis, which joins key parts with unescaped :).
RedisKvAdapter validates every MULTI/EXEC command receipt before certifying a reservation and
throws KvAtomicCommitUnconfirmedError on command errors, malformed replies, or unconfirmed
executions rather than returning { allowed: true }.
The memory store is for tests/development: it performs synchronous reservations, evicts expired keys
in bounded batches, and rejects new keys when its maxKeys cap is full. It holds no timers. Neither
adapter evicts a live quota to admit another key. Default fixed windows are aligned to epoch time; a
client can use two windows' quota around a boundary unless policy: { kind: 'gcra' } is enabled.
Separate limiters must use separate stores or KV prefixes unless they intentionally share a quota.
Hosts sharing a store need synchronized clocks (well within 5_000 ms for GCRA).
serve() supplies { remoteAddr: info.remoteAddr } to Hono on HTTP and TLS listeners, so Hono's
Deno getConnInfo sees the socket peer. A mounting host can pass the same ServiceEnvironment to
app.fetch(request, env). Without metadata, the default key is a shared unknown bucket; provide
metadata or a custom key for per-client quotas. The stage warns once through the request logger
(or the service package logger) when a selected request falls back to this global bucket.
IPv6 address keys share their /64 network by default, preventing interface-ID rotation from evading
quota or filling the memory store with keys within that network. ipv6Prefix accepts 0–128; 128
retains individual hosts. Canonicalization includes trusted XFF and retains IPv6 scope IDs.
IPv4-mapped IPv6 peers (::ffff:0:0/96) are converted to dotted IPv4 before prefix masking and
share only the corresponding native IPv4 quota. This keeps IPv4 clients independent on dual-stack
listeners and through proxies writing mapped forms. Native IPv4 and custom keys stay unchanged. This
does not alter socket metadata or proxy trust. Multiple IPv6 networks or attacker-controlled custom
keys can still exhaust capacity.
KV counters expire at the window boundary, but TTL limits lifetime rather than live key count.
Accepted writes refresh only the remaining window duration; rejections do not create or refresh
counters. Use backend capacity/admission controls and stable custom keys for untrusted inputs. The
memory store bounds live keys with maxKeys and rejects new keys when full.
Like the auth transport policy, proxy trust defaults off. trustProxy: (address) => ... explicitly
identifies trusted proxy addresses. XFF is walked right to left from the socket peer, stopping at
the first untrusted address. A client-supplied XFF from an untrusted socket is ignored. Trusted
proxies must overwrite or append the actual peer address; malformed or oversized chains fall back to
the socket address. This client-address policy does not enable auth protocol-header trust.
See Protect an anonymous service route for a shared KV example.
Procedure-level rate limits and request correlation
Use .withProcedureRateLimit() to enforce post-auth principal/tenant quotas or public
IPv6-/64-bucketed procedure quotas inside the oRPC procedure pipeline. The stage validates
limit, windowMs, ipv6Prefix, and RFC 0008 store.validate?.({ limit, windowMs })
synchronously at registration, rejects sharing the same RateLimitStore instance with HTTP-edge
.withRateLimit() (preventing 2× HTTP double-counting), and emits HTTP 429 plus a
Retry-After header (derived from decision.retryAt ?? decision.resetAt via oRPC's
ResponseHeadersPlugin) alongside a contract-defined ORPCError('RATE_LIMITED', ...) envelope.
import { createService } from '@netscript/service'; import { createMemoryRateLimitStore } from '@netscript/service/rate-limit'; const app = createService({}, { name: 'orders' }) .withLogger() .withProcedureRateLimit({ limit: 120, windowMs: 60_000, store: createMemoryRateLimitStore({ policy: { kind: 'gcra' } }), key: ({ principal, clientAddress, procedurePath }) => principal ? `${String(principal.claims.tenantId ?? 'global')}:${principal.subject}:${procedurePath.join('.')}` : `addr:${clientAddress ?? 'unknown'}:${procedurePath.join('.')}`, }) .withRPC() .build(); void app;
When .withLogger() and .withRPC() are combined, ServiceBuilder propagates the HTTP
requestId (X-Request-ID or the ID minted by loggerMiddleware) into LoggingPlugin and
ServiceHandlerContext.requestId, while wrapping both router and withRPC({ rpcRouter })
leaves idempotently per service (failing closed with ROUTER_CLIENT_CROSS_SERVICE_MOUNT on
cross-service remounts).
Non-listening start() lifecycle and procedure-level auth
Use ServiceBuilder.start() when hosting a service without binding a TCP listener. start()
verifies a clean composition-root async context (AsyncContextRootCaptureError if called inside an
active framework AsyncLocalStorage or non-root OpenTelemetry context), runs onStartup hooks,
tracks in-flight calls and eventIterator streams, and returns a StartedService handle whose
idempotent stop() refuses new calls, drains in-flight work within drainTimeoutMs, runs
onShutdown hooks in reverse order, and disconnects registered databases.
import { createService } from '@netscript/service'; import { createContractAuthorizer, type ProcedureAuthorizerPort } from '@netscript/service/auth'; import type { ContractPolicyContract, ServiceRouter } from '@netscript/service'; declare const contract: ContractPolicyContract; declare const router: ServiceRouter; const procedureFallback: ProcedureAuthorizerPort = { authorizeProcedure: ({ principal, procedurePath }) => ({ matched: true, decision: procedurePath[0] === 'public' || principal.scopes.includes('orders:read') ? { allow: true } : { allow: false, reason: 'authz.missing-scope:orders:read' }, }), }; const started = await createService(router, { name: 'orders' }) .withAuthz({ authorizer: createContractAuthorizer(contract, { fallback: procedureFallback }) }) .withRPC() .start({ drainTimeoutMs: 10_000 }); await started.stop();
ProcedureAuthorizerPort (authorizeProcedure) is invoked identically by HTTP
createContractAuthorizer() and the oRPC procedure pipeline for unmarked procedures (dual fallback
objects implementing both authorizeMatch and authorizeProcedure are rejected at construction).
Authenticated HTTP requests brand principals with a request-scoped VerifiedPrincipalRecord so
AuthenticatorPort runs once per HTTP request while closing cross-service, expired/NaN exp,
internal-audience, and post-request replay hazards.
Examples
Define a generated service entrypoint.
Define a generated service entrypoint.
import { defineService, type ServiceRouter } from '@netscript/service'; declare const router: ServiceRouter; const service = await defineService(router, { name: 'users', auth: { public: true, reason: 'Public example service' }, port: 3000, }); await service.stop();
Customize the builder before serving.
Customize the builder before serving.
import { createService, type ServiceRouter } from '@netscript/service'; declare const router: ServiceRouter; const service = await createService(router, { name: 'custom' }) .withCors({ origin: 'https://example.com' }) .withLogger() .withOpenAPI({ title: 'Custom API' }) .withDocs() .withRPC() .withHealth() .serve({ port: 3005 }); await service.stop();
Use health primitives directly in a host app.
Use health primitives directly in a host app.
import type { Hono } from 'hono'; import { createHealthHandler, type Database, healthChecks } from '@netscript/service'; declare const app: Hono; declare const db: Database; app.get('/health', createHealthHandler({ checks: [healthChecks.database(db)], }));
Add Package
deno add jsr:@netscript/service
Import symbol
import * as service from "@netscript/service";
Import directly with a jsr specifier
import * as service from "jsr:@netscript/service@^0.0.10";