iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / auth-worker / src / host-tokens.tsmain at 949894f

// host-tokens.ts — A TOKEN FOR ONE MIND HOSTNAME, FROM A MEMBER'S OWN SESSION. A program that
// holds a member's sign-in for the mind's API (the CLI) may need to prove that member to one of
// the mind's own hostnames, with a credential that opens nothing else: `iterate git-credential`
// hands one to git for `git.<zone>` (core/lib/src/cli/git.ts).
//
//   POST /oauth2/token
//     grant_type=urn:ietf:params:oauth:grant-type:token-exchange
//     subject_token=<the session's access token for the API>
//     subject_token_type=urn:ietf:params:oauth:token-type:access_token
//     resource=https://<a hostname of the mind>
//   → { access_token, issued_token_type, token_type: "Bearer", expires_in }
//
// This is OAuth token exchange (https://www.rfc-editor.org/rfc/rfc8693) with the resource of
// https://www.rfc-editor.org/rfc/rfc8707. The OAuth library's own token exchange is off, and
// refuses to change a token's resource; this file answers the grant type alone.
//
// THE TOKEN is signed by this Worker, as a key's token is (./key-tokens.ts), for that one
// hostname's origin. It ends when its subject token ends, so it is never more than the session it
// came from: an hour at most. There is no refresh token: the holder exchanges again.
//
// EVERY USE ASKS AGAIN (`hostTokenIdentity`): the session's grant must still be held, and its
// person must still be a member. So a removed member stops the token at its next request, and a
// sign-in that a member ended on /sessions, or a sign-out, stops it as it stops the session's own
// token: at the next read of the grant's row, which KV may answer from its cache for up to a
// minute at a place that read it just before.
import type { TokenIdentity } from "iterate/workers";
import { mindApiUrlOf } from "iterate/mind-api";
import { SignInMethod } from "iterate/principal";
import { jwtVerify, SignJWT } from "jose";
import { z } from "zod";
import { formOf, oauthError } from "./device/protocol.ts";
import { configOf, type Env, issuerOf } from "./env.ts";
import { isMember, isMemberByName } from "./members.ts";
import { mindHostResourceOf, tokenIdentity } from "./oauth.ts";

export const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";

/** A token with less than this left is no use to its holder: a clone outlives it. */
const LEAST_SECONDS = 60;

// The Worker's one signing key (./cookies.ts, ./key-tokens.ts). A host token's audience is a mind
// hostname's origin, which is never a cookie's word or the API's URL.
const signingKey = (env: Env) => new TextEncoder().encode(configOf(env).signingKey.exposeSecret());

const Claims = z.object({
  kind: z.literal("host-token"),
  sub: z.string().startsWith("user_"),
  /** The grant of the session that the token came from. */
  grant: z.string().min(1),
  email: z.string().min(1),
  method: SignInMethod,
  exp: z.number(),
});

const ExchangeForm = z.object({
  grant_type: z.literal(TOKEN_EXCHANGE_GRANT),
  subject_token: z.string().min(1).max(256),
  subject_token_type: z.literal(ACCESS_TOKEN_TYPE),
  requested_token_type: z.literal(ACCESS_TOKEN_TYPE).optional(),
  resource: z.string().min(1),
});

/** The token endpoint's answer to a token exchange, or null for any other grant type. */
export async function hostTokenResponse(env: Env, request: Request): Promise<Response | null> {
  const fields = await formOf(request.clone());
  if (fields.grant_type !== TOKEN_EXCHANGE_GRANT) return null;
  const form = ExchangeForm.safeParse(fields);
  if (!form.success)
    return refused(
      "invalid_request",
      "A token exchange here takes subject_token (an access token of this mind's API), subject_token_type and resource (the origin of a hostname of this mind).",
    );
  const config = configOf(env);
  const resource = mindHostResourceOf(config, form.data.resource);
  if (!resource)
    return refused("invalid_target", "The resource is not the origin of a hostname of this mind.");
  // a member's own session for the API: never a key's token, and never a token for another resource
  const subject = await tokenIdentity(
    env,
    form.data.subject_token,
    mindApiUrlOf(config.controlPlaneHostname),
  );
  if (!subject?.member || !subject.principal.email)
    return refused("invalid_request", "The subject token is not a member's live sign-in.");
  // a hostname stamps a person by how they signed in (core/boundary-worker/src/stamp.ts)
  if (!subject.method)
    return refused(
      "invalid_request",
      "This sign-in is older than the hostnames' sign-in and names no way of signing in. Sign in again.",
    );
  const seconds = subject.expiresAt - Math.floor(Date.now() / 1000);
  if (seconds < LEAST_SECONDS)
    return refused("invalid_request", "The subject token is about to end. Renew it first.");
  const token = await new SignJWT({
    kind: "host-token",
    grant: subject.grant,
    email: subject.principal.email,
    method: subject.method,
  } satisfies Omit<z.infer<typeof Claims>, "sub" | "exp">)
    .setProtectedHeader({ alg: "HS256" })
    .setIssuer(issuerOf(env))
    .setAudience(resource)
    .setSubject(subject.principal.actor)
    .setIssuedAt()
    .setExpirationTime(subject.expiresAt)
    .sign(signingKey(env));
  console.info({
    event: "auth.host-token-issued",
    actor: subject.principal.actor,
    grant: subject.grant,
    resource,
    seconds,
  });
  return Response.json(
    {
      access_token: token,
      issued_token_type: ACCESS_TOKEN_TYPE,
      token_type: "Bearer",
      expires_in: seconds,
    },
    { headers: { "cache-control": "no-store" } },
  );
}

/** Who a host token is, for the one mind hostname it was made for: a member, or nobody. The grant
 *  and the membership are read on every use. */
export async function hostTokenIdentity(
  env: Env,
  token: string,
  resource: string,
): Promise<TokenIdentity | null> {
  if (token.split(".").length !== 3 || !mindHostResourceOf(configOf(env), resource)) return null;
  const claims = await jwtVerify(token, signingKey(env), {
    issuer: issuerOf(env),
    audience: resource,
    algorithms: ["HS256"],
  }).then(
    ({ payload }) => Claims.safeParse(payload).data,
    () => undefined,
  );
  if (!claims) return null;
  // As the session's own token is read (./oauth.ts `grantIsMembers`): a passkey's person is a
  // member by any rule, and any other way's only by name.
  const member =
    claims.method === "passkey"
      ? await isMember(env, claims.email)
      : await isMemberByName(env, claims.email);
  if (!member || !(await grantKept(env, claims.sub, claims.grant))) return null;
  return {
    principal: { actor: claims.sub, email: claims.email },
    grant: claims.grant,
    expiresAt: claims.exp,
    member: true,
    method: claims.method,
  };
}

/** Whether the OAuth library still keeps a grant: it was not ended, and has not lapsed. READ BY
 *  ITS OWN KEY, as the library reads it for a token of its own, and not from the list of a
 *  person's grants: KV's list shows a new key late, so a token made right after a sign-in was
 *  nobody's for some seconds (seen on a dev mind, 26 Nov 2026). The key's form is the library's
 *  (`grant:<userId>:<grantId>`); ./host-tokens.test.ts fails when a new version changes it. */
const grantKept = async (env: Env, userId: string, grantId: string) =>
  (await env.OAUTH_KV.get(`grant:${userId}:${grantId}`)) !== null;

// RFC 8693 §2.2.2: `invalid_request` for a subject token that is not taken, `invalid_target` for a
// resource that is not.
function refused(error: "invalid_request" | "invalid_target", description: string) {
  console.info({ event: "auth.host-token-refused", error, description });
  return oauthError(error, description);
}