Skip to content

Sample: Session Exchange

I want my own login method (Apple/Google ID token, email link) without rebuilding cookies, JWTs and rate limits.

An anonymous write handler verifies an identity and returns { kind: "auth-session", session }. The app lists it under auth.sessionExchangeHandlers; POST /api/auth/session-exchange runs it and mints the session like /auth/login (token, cookies). The rate limit counts per IP and method and is not reset on success, because the route cannot tell whose code was right. By default it reuses the login limiter; set auth.sessionExchangeRateLimit to a larger limiter, or null to turn it off (for example when the methods carry signed tokens).

auth: {
membershipQuery: "tenant:query:memberships",
loginHandler: "auth-email-password:write:login",
sessionExchangeHandlers: { code: "demo-exchange:write:code" },
},

The client calls POST /api/auth/session-exchange with { method: "code", payload: { ... } }.

  1. Only listed handlers can issue a session. The route resolves method against the map (own keys only); the handler QN never comes from the client.
  2. The handler owns verification. The demo compares a fixed code; a real handler verifies the ID token signature and audience first, then calls sessionForVerifiedUser(ctx, { email }) (or { userId }) for the login gates: account status, membership choice, claims. A lookup by email only issues a session for a verified address (otherwise a pre-registered attacker account would be taken over by the victim), a lookup by userId trusts your own identity link. There is no password or lockout gate, so accept only credentials that cannot be guessed: a signed ID token or a long random one-time token. A short code (six digits by mail) needs its own attempt counter per identity in the handler; the route only knows the IP, and a per-IP bucket does not stop a distributed guess. There is no MFA gate: boot aborts when auth-mfa is mounted together with sessionExchangeHandlers.
  3. Anything but auth-session is rejected. An MFA challenge or foreign result yields 500 and no cookie.
  4. Errors map like login. details.reason goes through loginErrorStatusMap.
  5. Grant SYSTEM to the one handler, hide it from agents. escapeHatch: { grants: ["systemIdentity"] } on the exchange handler, not r.systemScope() on the feature, and agent: { expose: false } because the payload is a credential.
  • End-to-end over HTTP: exchange returns a token that authenticates a query
  • Wrong code: 401 via invalid_credentials
  • Restricted user: no session
  • Unknown method: 400

The feature entry point — embedded straight from the source file, so the code here is exactly what runs. Multi-file samples keep their remaining files next to it on GitHub (link below):

// Session Exchange Sample
//
// An app-defined login method: an anonymous write handler verifies an identity
// and returns { kind: "auth-session", session }; the framework route mints the
// session (token, cookies, rate limit) exactly like /auth/login.
//
// What to copy into your own app:
//
// auth: {
// membershipQuery: "tenant:query:memberships",
// sessionExchangeHandlers: { code: "demo-exchange:write:code" },
// },
//
// Only handlers listed in sessionExchangeHandlers can cause a session to be
// issued, so a handler that merely returns a session-shaped object elsewhere
// stays harmless. The demo code check stands in for verifying an ID token;
// sessionForVerifiedUser then runs the login gates after the identity proof
// (account status, membership choice, claims).
import { sessionForVerifiedUser } from "@cosmicdrift/kumiko-bundled-features/auth-email-password";
import { defineFeature } from "@cosmicdrift/kumiko-framework/engine";
import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
import { z } from "zod";
export const DEMO_EXCHANGE_CODE = "246810";
export const DEMO_EXCHANGE_QN = "demo-exchange:write:code";
export const INVALID_CREDENTIALS_REASON = "invalid_credentials";
export const demoExchangeFeature = defineFeature("demo-exchange", (r) => {
r.requires({ features: ["user", "tenant"] });
r.writeHandler({
name: "code",
schema: z.object({ email: z.email(), code: z.string().min(1) }),
access: { roles: ["anonymous"] },
escapeHatch: {
grants: ["systemIdentity"],
reason:
"Unauthenticated exchange has no caller identity yet — sessionForVerifiedUser looks up the user and resolves the membership as SYSTEM before a session exists.",
},
// The payload carries a credential (code or ID token) that must never enter an LLM transcript.
agent: { expose: false },
handler: async (event, ctx) => {
if (event.payload.code !== DEMO_EXCHANGE_CODE) {
return writeFailure(
new UnprocessableError(INVALID_CREDENTIALS_REASON, {
i18nKey: "demo-exchange.errors.invalidCredentials",
}),
);
}
return sessionForVerifiedUser(ctx, { email: event.payload.email });
},
});
});

📄 On GitHub: samples/recipes/session-exchange/src/feature.ts