Skip to main content
NetScriptdocs Search docs ⌘K v0.0.9
Browse documentation
View as Markdown

Protect routes with authz

In this chapter you guard the workspace service's member list. You declare the members procedure once with baseContract.route(...).meta({ access: ... }), so its HTTP method, path, input and output schemas and authorization requirements live on the contract value that the service and its clients share. createContractAuthorizer() turns that declaration into the service builder's .withAuthn() / .withAuthz() middleware, and the route fails closed: no credential returns 401 before the handler runs, and a valid credential without the right scope returns 403.

  1. 1 · Scaffold
  2. 2 · Auth
  3. 3 · Workspace data
  4. 4 · Provision job
  5. 5 · Route authz
  6. 6 · Deploy

What you will build

A guarded GET /api/workspace/:workspace/members route. One oRPC procedure contract declares its path, typed workspace/limit/offset input, typed output, and required workspace:read scope. The service implements that contract and gates it with .withAuthn(), which turns each request into a Principal, and .withAuthz(), which enforces the procedure metadata. At the end:

  • an unauthenticated request returns 401 UNAUTHORIZED;
  • a request with the wrong scope returns 403 FORBIDDEN;
  • a correctly scoped request returns 200 with a typed member list.

These are the three outcomes the framework's own test asserts.

Before you begin

  • The workspace service and its typed contracts from chapter 1.
  • The Member model and the workspaceDb client from chapter 3; the route lists members from that datasource.
  • The contract metadata vocabulary ships in @netscript/contracts and the route-authz seam in @netscript/service/auth. Neither needs the auth plugin to type-check, but you run the service under Aspire to call it.

Confirm the workspace still builds before you change it:

Shell
# In my-workspace/
deno task check

Step 1 — Declare access on the procedure contract

Give the route a typed identity and policy first. Create the procedure in the shared contracts/ tree so the service and every client import the same object. The route uses oRPC's {workspace} placeholder; the default service REST mount adds /api at runtime.

contracts/versions/v1/workspace.contract.tsTypeScript
// contracts/versions/v1/workspace.contract.ts
import { implement } from '@orpc/server';
import { baseContract } from '@netscript/contracts';
import { z } from 'zod';

const MembersInput = z.object({
  workspace: z.string().min(1),
  limit: z.coerce.number().int().positive().max(100).default(20),
  offset: z.coerce.number().int().nonnegative().default(0),
});

const Member = z.object({
  id: z.string(),
  workspaceId: z.string(),
  subject: z.string(),
  role: z.string(),
});

const MembersOutput = z.object({
  workspace: z.string(),
  limit: z.number().int(),
  offset: z.number().int(),
  subject: z.string(),
  members: z.array(Member),
});

export const WorkspaceContractV1 = {
  members: baseContract
    .route({ method: 'GET', path: '/workspace/{workspace}/members' })
    .meta({
      access: {
        authentication: 'required',
        authorization: { scopes: ['workspace:read'] },
      },
    })
    .input(MembersInput)
    .output(MembersOutput),
};

export const WorkspaceV1 = implement(WorkspaceContractV1);

The .meta({ access: ... }) block is the guard's source of truth. It uses the NetScriptProcedureMeta.access vocabulary: authentication is none, optional or required, and authorization may declare readonly scopes and roles. There is no separate path-policy map to keep in sync with the route.

@netscript/contracts — procedure access metadata
Name · TypeDescription
.meta({ access })NetScriptProcedureMeta Stores access policy on the procedure that owns the route and schemas.
authentication'none' | 'optional' | 'required' Declares whether the operation is public, optional-auth, or authenticated.
authorization.scopesreadonly string[] Every declared scope must be present on the authenticated Principal.
authorization.rolesreadonly string[] Every declared role must be present on the authenticated Principal.

Step 2 — Build the authenticator and contract authorizer

Define the credentials, then build the authorizer from the contract. A read credential carries workspace:read; a write credential doesn't. The authorizer reads the required scope from WorkspaceContractV1.members, so there is no duplicated path matcher:

services/workspace/src/auth.tsTypeScript
// services/workspace/src/auth.ts
import {
  createContractAuthorizer,
  createStaticCredentialAuthenticator,
} from '@netscript/service/auth';
import { WorkspaceContractV1 } from '../../../contracts/versions/v1/workspace.contract.ts';

export const authenticator = createStaticCredentialAuthenticator({
  credentials: {
    read: {
      subject: 'user:reader',
      scopes: ['workspace:read'],
      roles: ['reader'],
    },
    write: {
      subject: 'user:writer',
      scopes: ['workspace:write'],
      roles: ['writer'],
    },
  },
});

export const authorizer = createContractAuthorizer(WorkspaceContractV1);
@netscript/service/auth — the route-authz surface
Name · TypeDescription
createStaticCredentialAuthenticator(opts)AuthenticatorPort Maps bearer tokens to principals — each credential carries a subject, scopes, and roles. Good for tests and machine-to-machine callers.
createContractAuthorizer(contract, { fallback?, rawRoutes?, retiredPaths? })ContractPolicyAuthorizerPort Traverses procedure-local access metadata and binds it to the builder's real REST/RPC paths and aliases. rawRoutes declares exact, authentication-required raw routes. Unknown guarded requests return typed 404 after authentication; retiredPaths declares exact paths returning 410.
createScopeAuthorizer(opts)MatchAwareAuthorizerPort Supported legacy path-rule authorizer; standalone, or a fallback only when a matched procedure has no metadata.
.withAuthn({ authenticator, protect?, allowAnonymous? })builder stage protect defaults to ['/api']; allowAnonymous defaults to ['/health'].
.withAuthz({ authorizer, denyByDefault? })builder stage denyByDefault defaults to true — fail closed when no decision is reachable.

Distinguish a missing endpoint from a permission denial

Once authentication succeeds, an unknown procedure under a guarded prefix returns HTTP 404 with JSON code: "procedure_not_found". For an endpoint you deliberately removed, pass exact mounted paths to createContractAuthorizer(WorkspaceContractV1, { retiredPaths: ['/api/v1/workspace', '/api/rpc/v1/workspace/members'] }). Those paths return 410 with { "error": "GONE", "message": "authz.procedure-retired", "code": "procedure_retired" }. HTTP clients can use that stable code to show “client too old” and ask the user to upgrade. These middleware errors occur before oRPC dispatch; inspect the HTTP JSON code rather than assume a contract-defined oRPC error or parse the message.

An anonymous request to either path still gets the existing 401 refusal, without a procedure code. A retired declaration requires authentication even outside protect or inside allowAnonymous. Existing procedures, raw-route policies and internal audience guards win over retirement: insufficient scopes/roles still return 403, and public procedures remain public.

Retired declarations are exact canonical absolute paths, apply to every method and ignore query strings. List REST, RPC and aliases separately. Parameters, wildcards, encoded paths, trailing slashes, dot segments, duplicate declarations and query/fragment syntax are rejected at construction. A declared path does not include siblings or descendants. Undeclared paths outside protected coverage keep their current behavior. See the service reference for response shapes and PROCEDURE_ERROR_CODES / ProcedureErrorCode exports.

defineService() requires an explicit auth policy and refuses to start without one. With auth installed, netscript service add wires browserAuthenticator and createContractAuthorizer(router) into the generated entrypoint. In that generated posture:

  • procedures that declare access: { authentication: 'none' } stay public;
  • a protected procedure declares authentication: 'required', as the members procedure does;
  • /health, /api/openapi.json and /api/docs stay anonymous health and discovery endpoints. Public discovery doesn't grant access to protected REST or RPC handlers.

The static read and write credentials above are local test fixtures. For signed-in users, keep the generated browserAuthenticator from auth/service.ts; it verifies the session bearer with the auth service. The low-level builder in Step 3 installs its guards explicitly. Existing standalone createScopeAuthorizer() consumers can keep their path rules.

Public services

For a deliberately public service, record the opt-out in its defineService() options:

TypeScript
// Explicit public policy (not a policy for the protected members service).
import type { ServiceAuthPolicy } from '@netscript/service/auth';

const auth = {
  public: true,
  reason: 'Public status service with no protected operations',
} satisfies ServiceAuthPolicy;

Pass that value as auth to defineService(router, { name: 'status', auth }). It disables the service guards, so use it only when every operation may be anonymous. To find opted-out services, search their source for public: true. Explicit service posture covers the migration from omitted auth.

Migrating path rules

If you are migrating older path rules, pass createScopeAuthorizer() as fallback. Contract metadata always wins on disagreement. The fallback is consulted only for a matched procedure with no access metadata; if no fallback rule matches, the adapter denies, even when that fallback would allow unmatched paths in standalone mode.

Step 3 — Implement the contract and layer the guard

Bind a handler to WorkspaceV1.members, then pass the router to the service builder. The handler runs only for an authenticated, authorized caller, and its input and output are typed from the same procedure that owns the access declaration:

services/workspace/src/main.tsTypeScript
// services/workspace/src/main.ts
import { os } from '@orpc/server';
import { createService, type ServiceHandlerContext } from '@netscript/service';
import { WorkspaceV1 } from '../../../contracts/versions/v1/workspace.contract.ts';
import { workspaceDb } from './db.ts'; // the chapter 3 workspace client
import { authenticator, authorizer } from './auth.ts';

const workspaceV1 = WorkspaceV1.$context<ServiceHandlerContext>();

const router = os.router({
  members: workspaceV1.members.handler(async ({ input, context }) => {
    // Auth is runtime-configured, so the public context type is intentionally optional.
    // This procedure is guarded; narrow once before using the principal.
    if (!context.principal) throw new Error('authenticated principal required');

    const members = await workspaceDb.member.findMany({
      where: { workspaceId: input.workspace },
      take: input.limit,
      skip: input.offset,
      orderBy: { createdAt: 'asc' },
    });

    return {
      workspace: input.workspace,
      limit: input.limit,
      offset: input.offset,
      subject: context.principal.subject,
      members,
    };
  }),
});

const app = createService(router, { name: 'workspace' })
  .withRPC()
  .withAuthn({ authenticator })
  .withAuthz({ authorizer })
  .build();

export { app };

The builder binds the contract policy to its actual REST and RPC mounts. If you customize .withRPC({ apiPath, rpcPath, rpcAliases, deprecatedRpcRoutes }), one shared resolver uses those effective paths for both authn and authz, so you don't repeat them in the policy.

Step 4 — Call the guarded service with the generated typed client

Once chapter 2 installs auth, the generated auth/bff.ts provides createBrowserSessionClient() and browserSessionContext(). Use them in the app's server-side request handler; the contract still supplies the procedure input and output types:

apps/dashboard/routes/examples/workspace/(_lib)/workspace-session.tsTypeScript
// apps/dashboard/routes/examples/workspace/(_lib)/workspace-session.ts
import { WorkspaceContractV1 } from '@my-workspace/contracts';
import { browserSessionContext, createBrowserSessionClient } from '../../../../../../auth/bff.ts';

const workspaceClient = createBrowserSessionClient(WorkspaceContractV1, 'workspace', 'workspace');

export async function loadWorkspaceMembers(request: Request, workspace: string) {
  return await workspaceClient.members(
    { workspace, limit: 20, offset: 0 },
    { context: browserSessionContext(request) },
  );
}

// The same response boundary used by generated server-side session routes.
export async function handleWorkspaceMembers(request: Request, workspace: string) {
  const headers = { 'cache-control': 'no-store' };
  if (!browserSessionContext(request).accessToken) {
    return Response.json({ authenticated: false }, { status: 401, headers });
  }
  try {
    return Response.json(await loadWorkspaceMembers(request, workspace), { headers });
  } catch (error) {
    if (error instanceof Error && 'status' in error && (error.status === 401 || error.status === 403)) {
      return Response.json({ authenticated: false }, { status: error.status, headers });
    }
    throw error;
  }
}

Replace @my-workspace/contracts with your generated workspace's contracts package name.

The helper reads the HttpOnly session cookie on the server and adds its opaque bearer to the SDK call. The client handles discovery, RPC serialization, transport and errors, so you need no custom fetch or Authorization header wrapper. Call handleWorkspaceMembers() from the current request: it returns only member data or a redacted authentication failure, following the generated session route's response boundary:

  • no session returns HTTP 401;
  • an upstream authorization denial returns 403;
  • an allowed call returns 200.

The SDK credential reference shows the public contribution API the generated helper composes. A required procedure with no bearer fails locally before transport, and an anonymous caller that reaches the service receives 401. A valid session without workspace:read receives 403, and an authorized session returns the typed members result. For the static fixture above, the equivalent SDK call uses read or write as its accessToken; these strings are not production sessions.

This interactive call belongs to the app interface. Workers, sagas and triggers run independently under the installation service identity, not an open app or a user's session.

Step 5 — Call the guarded route

The guard produces three distinct responses, each asserted in the framework's builder-auth_test.ts. With the service running under Aspire (aspire start from aspire/), call the route for team ws-1:

Inspect the live operation with list_api_services → list_service_operations → get_operation_schema. Then use the generated server-side session client from Step 4:

TypeScript
// Static credentials are a local fixture; production uses the current server session.
const members = await workspaceClient.members(
  { workspace: 'ws-1', limit: 2, offset: 0 },
  { context: { accessToken: 'read' } },
);

The app handler returns 401 when no session credential is present. With the static write credential, the service rejects the call with 403 because it lacks workspace:read. The read credential carries that scope and returns the typed result. The SDK may reject a required call without a bearer before sending it; that is separate from the app handler's HTTP 401 boundary.

The 200 body echoes the values the contract parsed: the typed workspace path param, the typed limit/offset page, the authenticated subject, and the member rows from chapter 3:

JSON
{
  "workspace": "ws-1",
  "limit": 2,
  "offset": 0,
  "subject": "user:reader",
  "members": [
    { "id": "mem_01", "workspaceId": "ws-1", "subject": "user:alice", "role": "member" }
  ]
}

An empty members array is still a 200: the guard passed and the team has no rows yet. Provision one with the chapter 4 job. A 401 or 403 means the request never reached the query.

Verify your progress

The typed SDK calls and the Step 4 app handler verify the service policy through the generated BFF client. Unauthenticated calls must fail closed and scoped calls must return typed member data:

  • [ ] contracts/versions/v1/workspace.contract.ts exports WorkspaceContractV1 with typed input, output, and .meta({ access: ... }) requiring workspace:read.
  • [ ] services/workspace/src/auth.ts defines the authenticator and constructs the authorizer from WorkspaceContractV1.
  • [ ] The workspace service implements WorkspaceV1.members, calls .withRPC(), and applies .withAuthn() and .withAuthz().
  • [ ] The handler reads typed input.workspace, input.limit, and input.offset; it does not parse the URL by hand.
  • [ ] An unauthenticated request returns 401 UNAUTHORIZED (missing-credential).
  • [ ] Bearer write returns 403 FORBIDDEN (authz.missing-scope:workspace:read).
  • [ ] Bearer read returns 200 with a body carrying workspace, limit, and subject.
  • [ ] GET /health still answers without a credential.
  • [ ] The Step 4 handleWorkspaceMembers() app response returns 401 without a session cookie, 403 with the static fixture cookie __Host-ns_session=write, and 200 with __Host-ns_session=read, through the generated typed BFF client and without custom fetch.
  • [ ] Production calls use the current verified session's opaque bearer, rather than the static fixture credentials, and return only member data to the browser.

What you built

A guarded, typed members procedure. WorkspaceContractV1.members owns the HTTP path, the typed input and output, and the required workspace:read scope; the service implements it and enforces its policy with createContractAuthorizer(). A 401 for an anonymous request, a 403 for the wrong scope and a 200 for a scoped one prove it. The URL, its typed data and its authorization gate come from one contract, checked by the compiler and by the framework's auth tests. This is route-level scope authorization, not org or role RBAC: tenancy stays in your code.

Next steps

  • Run the whole app. Chapter 6 · Deploy runs the authenticated workspace locally under Aspire.
  • Reuse the contract on the client. A typed SDK derived from WorkspaceContractV1 exposes the same members procedure and metadata. If you rename that procedure key, its contract-local metadata follows it, and a stale SDK reference to the old key fails to type-check.
Search all documentation

Type a term to search the documentation.