Add auth and a session
In this chapter you give my-workspace/ an identity layer: you add the official auth plugin,
choose the interactive KV-backed authentication backend, and check the session
endpoints of the auth-api service at the URL Aspire prints. You select the backend with one environment
variable, and the contract is identical for every backend, so switching providers later is a
configuration change.
What you will build
The auth plugin installed, the interactive kv-oauth backend selected with no auth SQL
tables, and the auth-api service answering at the URL Aspire prints. At the end,
GET /api/v1/auth/session and GET /api/v1/auth/me report "no session yet" before login, which
proves the backend is composed and the session endpoints are wired.
Before you begin
You need the workspace from chapter 1 with aspire start
running: the auth plugin contributes a service and KV-backed sessions that run through
the Aspire graph. Check that the base is up:
# In my-workspace/, with `aspire start` up in another terminal
netscript service list
netscript plugin doctor
Step 1 — Add the auth plugin
The auth plugin is an official plugin, installed the same way as workers, sagas and
triggers. From the workspace root:
netscript plugin install @netscript/plugin-auth
The installer scaffolds @netscript/plugin-auth into plugins/, registers it, and adds three
things to your workspace: KV-backed session storage, a service entry that becomes the
auth-api service, and the /api/v1/auth/* routes. The default kv-oauth backend contributes no
Prisma schema or SQL requirement. Confirm it landed:
netscript plugin list
Aspire allocates the service endpoint. Use the URL Aspire prints or list_api_services to find
auth-api. The app's generated BFF owns the browser callback, so register
<app-origin>/auth/callback with the provider. Use the app URL Aspire reports; update both the
provider registration and the configured redirect URI if that URL changes. A fixed external
callback origin is a deployment choice, not a framework port default.
Step 2 — Choose a backend with NETSCRIPT_AUTH_BACKEND
The NETSCRIPT_AUTH_BACKEND environment variable (or the auth.backend appsettings key) selects the
active backend. Three backends are valid. The default, kv-oauth, is the only one that drives
an interactive sign-in.
| Name · Type | Description |
|---|---|
kv-oauthinteractive (default) |
Full OAuth/OIDC redirect flow. Real signin + callback, KV-backed sessions with refresh-on-read, signout. The only backend that implements InteractiveFlowPort. Package @netscript/auth-kv-oauth. |
workosnon-interactive |
WorkOS AuthKit sealed cookie under NETSCRIPT_AUTH_COOKIE_NAME (default __Host-ns_session). The CLI WorkOS preset explicitly selects wos-session to match AuthKit. Subject-wide logout uses a durable KV fence and background upstream cleanup. Validates an existing session; signin/callback return AUTH_PROVIDER_ERROR. Package @netscript/auth-workos. |
better-authnon-interactive |
better-auth over Prisma. Validates an existing session; signin/callback return AUTH_PROVIDER_ERROR. Package @netscript/auth-better-auth. |
A team workspace needs users to log in, so this track uses the interactive default. Make the choice explicit in your environment:
export NETSCRIPT_AUTH_BACKEND=kv-oauth
Step 3 — Confirm the backend's storage requirements
This track uses kv-oauth, which stores sessions in KV and contributes no auth.prisma schema.
Skip the auth database migration and continue to Step 4. The primary Postgres from chapter 1
remains available for other application data.
Only the non-interactive better-auth backend contributes auth.prisma and its four models:
AuthUser → auth_users, AuthSession → auth_sessions, AuthAccount → auth_accounts, and
AuthVerification → auth_verifications. If you intentionally choose that backend in another
application, select it before installation (or reinstall with --force after changing it), then
run netscript db init, netscript db generate and netscript db status with Aspire running.
WorkOS verifies sealed cookies and keeps durable revocation state in KV; it also contributes no
SQL schema.
Step 4 — Configure the kv-oauth backend
The kv-oauth backend needs a real OAuth/OIDC provider (a client id, a secret and a redirect URI)
and a key that protects the session token at rest. Set them before you start the service:
# Selects the interactive backend
export NETSCRIPT_AUTH_BACKEND=kv-oauth
# Provider credentials (e.g. a Google or GitHub OAuth app)
export NETSCRIPT_AUTH_CLIENT_ID=your-client-id
export NETSCRIPT_AUTH_CLIENT_SECRET=your-client-secret
export NETSCRIPT_AUTH_REDIRECT_URI="$APP_URL/auth/callback"
# Required for kv-oauth: missing key material is a startup error
export NETSCRIPT_AUTH_KV_OAUTH_KEY=<base64url-encoded-32-byte-secret>
Set APP_URL to the app URL Aspire prints. Under Aspire, the AppHost injects the listener's
PORT; there is no fixed auth service port to export.
Step 5 — Compose the backend in code
When you wire the backend yourself, for a custom service entry or a test, the interactive kv-oauth
backend is one await call. You pass a provider preset from providers.* and get back an object
that satisfies the AuthBackendPort seam defined by @netscript/plugin-auth-core (and, because it
is kv-oauth, the optional InteractiveFlowPort):
// services/auth/src/backend.ts
import { createKvOAuthBackend, getRequiredEnv, providers } from '@netscript/auth-kv-oauth';
// providers.google(...) is a preset that fills the OIDC endpoints for you.
export const backend = await createKvOAuthBackend({
provider: providers.google({
clientId: getRequiredEnv('NETSCRIPT_AUTH_CLIENT_ID'),
clientSecret: getRequiredEnv('NETSCRIPT_AUTH_CLIENT_SECRET'),
redirectUri: getRequiredEnv('NETSCRIPT_AUTH_REDIRECT_URI'),
}),
});
// backend implements AuthBackendPort AND the optional InteractiveFlowPort,
// so the auth-api signin + callback endpoints are live on this backend.
console.log(backend.name); // 'kv-oauth'// Same factory, but define the OIDC provider yourself when your IdP is
// not one of the built-in presets.
import { createKvOAuthBackend, defineOAuthProvider, getRequiredEnv } from '@netscript/auth-kv-oauth';
const provider = defineOAuthProvider({
id: 'my-idp',
clientId: getRequiredEnv('NETSCRIPT_AUTH_CLIENT_ID'),
clientSecret: getRequiredEnv('NETSCRIPT_AUTH_CLIENT_SECRET'),
authorizationEndpoint: getRequiredEnv('NETSCRIPT_AUTH_AUTHORIZATION_ENDPOINT'),
tokenEndpoint: getRequiredEnv('NETSCRIPT_AUTH_TOKEN_ENDPOINT'),
userInfoEndpoint: getRequiredEnv('NETSCRIPT_AUTH_USERINFO_ENDPOINT'),
redirectUri: getRequiredEnv('NETSCRIPT_AUTH_REDIRECT_URI'),
scopes: ['openid', 'profile', 'email'],
});
export const backend = await createKvOAuthBackend({ provider });@netscript/plugin-auth-core defines the seam the auth plugin composes against: the
AuthBackendPort contract and the registry helpers that resolve one backend from many.
| Name · Type | Description |
|---|---|
AuthBackendPorttype |
The contract every backend implements — the auth-api surface is identical across all three backends because they all satisfy this port. |
createAuthBackendRegistry / resolveBackendfunction |
Build a registry of named backends and resolve the single active one (DEFAULT_AUTH_BACKEND_NAME is the fallback). |
AuthSessiontype |
The normalized session the store persists — id, subject, state, scopes, claims, issuedAt / expiresAt. |
createHmacSessionTokenCryptofunction |
HMAC-signs the opaque session token so the cookie value cannot be forged. |
authContractV1contract |
The six-route auth contract: signin, signout, revokeSession, callback, session, me. |
Step 6 — Verify a session through the app
The auth contract has six operations: signin, signout, revokeSession, callback, session
and me. Inspect the live service with list_api_services → list_service_operations →
get_operation_schema, selecting the auth-api resource and its actual operation identifiers.
Open the generated Fresh app at the URL Aspire prints. Visit /auth/signin; the app routes the
provider's callback through /auth/callback and keeps the session cookie on its own origin.
/auth/session reports the redacted session state. Before login it reports no active session;
after login it reports the authenticated principal.
Server-side loaders call services with createBrowserSessionClient from the generated
auth/bff.ts, passing browserSessionContext(request) for each incoming request. Keep the bearer
on the server; chapter 5 uses that client for the guarded workspace operation.
netscript plugin doctor
netscript contract list
deno task check
- [ ]
auth-apiis healthy at its allocated endpoint in Aspire. - [ ] MCP discovery lists all six auth operations.
- [ ] The generated app's
/auth/sessionreports no session before login. - [ ] The provider returns through the app callback and the session becomes authenticated.
- [ ]
deno task checkpasses.
For HTTP cookie-jar diagnostics outside the app, follow the auth recipe.
What you built
An identity layer for your workspace: the auth plugin composed onto the interactive kv-oauth
backend, KV-backed sessions with no auth SQL tables, and the auth-api service answering at the URL Aspire prints with
the six-route contract. The app can now tell a signed-in team member from a stranger. Next, you give
it something to protect: an isolated database for team records.