Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

8.7 KB
Raw Blame
/**
 * Auth middleware: `Authorization: Bearer <local API token>` -> the built-in admin, or
 * session cookie -> auth_sessions row -> user; either way the user is injected into c.var.
 *
 * The Bearer path authenticates the boot's local API token (`<root>/api-token`, see
 * auth/api-token.ts) as the admin — the CLI's and agents' machine-local credential; it
 * applies to every route behind this middleware, SSE endpoints included (the CLI
 * consumes SSE via fetch with headers). A Bearer header that does not match fails the
 * request rather than falling back to the cookie: silently downgrading a wrong explicit
 * credential would mask misconfiguration. A few writes refuse the token all the same and take a
 * person's sign-in (requireHuman).
 *
 * Accessing a protected API while logged out -> 401 `{error:{code:"unauthorized"}}`.
 * CSRF: SameSite=Lax plus a Content-Type an HTML form cannot forge (see jsonOnlyWrites).
 * That guard stays for Bearer requests too — the CLI always sends application/json.
 */
import type { MiddlewareHandler } from "hono";
import { getCookie, setCookie } from "hono/cookie";
import { HttpError } from "../http/errors.js";
import type { UserRow } from "../db/repos/users.js";
import type { SessionVia } from "./service.js";
import type { Auth } from "../mechanisms/identity.js";

/** Session cookie name. */
export const SESSION_COOKIE = "penguin_session";

/**
 * Session cookie attributes, shared by every path that sets one. `maxAge` comes from the
 * service that issues the sessions, never written here: the ROW carries the authoritative
 * expiry, and a cookie that expired first would log someone out mid-session.
 */
export function cookieOptions(
  c: { req: { url: string; header(name: string): string | undefined } },
  ttlMs: number,
  trustProxy: boolean,
) {
  // `x-forwarded-proto` is caller-supplied and untrusted unless the deployment opts in
  // (config.trustProxy — the same gate hmr/routes.ts uses, and for the same reason). Trusting
  // it on a plain-HTTP bind would let anyone reaching the port get a Secure cookie back, which
  // the browser then refuses to send over that connection: a sign-in that never takes.
  const proto = trustProxy
    ? (c.req.header("x-forwarded-proto") ?? new URL(c.req.url).protocol.replace(":", ""))
    : new URL(c.req.url).protocol.replace(":", "");
  return {
    httpOnly: true,
    sameSite: "Lax" as const,
    path: "/",
    maxAge: Math.floor(ttlMs / 1000),
    ...(proto === "https" ? { secure: true } : {}),
  };
}

/** Hono env: variables injected by the auth middleware. */
export type AppEnv = {
  Variables: {
    user: UserRow;
    /** How the current session was established — see {@link SessionVia}. */
    sessionVia: SessionVia;
  };
};

/** Gets the current user (available after authMiddleware). */
export function currentUser(c: { var: { user: UserRow } }): UserRow {
  return c.var.user;
}

export function authMiddleware(auth: Auth, trustProxy: boolean): MiddlewareHandler<AppEnv> {
  return async (c, next) => {
    // Bearer first: an explicit credential on the request outranks ambient cookies, and
    // a wrong one is an error, never a silent fallback (see the module doc).
    const bearer = bearerToken(c.req.header("authorization"));
    if (bearer !== null) {
      const viaToken = auth.authenticateApiToken(bearer);
      if (!viaToken) {
        throw new HttpError(401, "unauthorized", "Invalid API token.");
      }
      c.set("user", viaToken.user);
      c.set("sessionVia", viaToken.via);
      await next();
      return;
    }
    const token = getCookie(c, SESSION_COOKIE);
    const authed = token ? auth.authenticateWithMeta(token) : null;
    if (!authed) {
      throw new HttpError(401, "unauthorized", "Not signed in or the sign-in has expired.");
    }
    // Sliding renewal: the session's expiry was topped up in place, so refresh the cookie's
    // own max-age to match. The token value is unchanged — same session, longer life.
    if (authed.renewed && token) {
      setCookie(c, SESSION_COOKIE, token, cookieOptions(c, auth.sessionTtlMs, trustProxy));
    }
    c.set("user", authed.user);
    c.set("sessionVia", authed.via);
    await next();
  };
}

/** The token of an `Authorization: Bearer <token>` header (scheme matched case-insensitively); null for any other shape. */
export function bearerToken(header: string | undefined): string | null {
  if (header === undefined) return null;
  const m = /^Bearer\s+(.+)$/i.exec(header.trim());
  return m === null ? null : m[1]!.trim();
}

/**
 * Refuses the local API token on a write that only a person may make: 403 `human_required`. A
 * person's sign-in — a cookie session, from the Web App, `penguin auth login` or
 * `penguin auth token` — passes. Every tool subprocess of a server-driven Session holds that token
 * as `ADELIE_API_TOKEN`, so these are the writes an Agent must not make from its own shell:
 *
 * - who can reach an Agent from outside — its API switch, keyless access and approval mode, its
 *   keys, the API tab's Try it, and the admin's `agentApiEnabled` (http/routes/agent-api.ts,
 *   amsp/try-route.ts, http/routes/admin-settings.ts).
 *
 * This narrows the credential the harness hands an Agent; it is not a boundary. A process that
 * runs as the data root's OS user outside the sandbox can mint a sign-in of its own
 * (`penguin auth token`), or reset a password with the token and sign in. The sandbox is the
 * boundary. A per-Session credential (design PR #235) is the structural fix: when it lands, this
 * check becomes "a Session's credential is refused, a person's login is not", and the routes
 * calling it do not change.
 */
export function requireHuman(c: { var: { sessionVia: SessionVia } }): void {
  if (c.var.sessionVia === "token") {
    throw new HttpError(
      403,
      "human_required",
      "Only the signed-in user can do this, in the app; an API token cannot.",
    );
  }
}

const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);

/**
 * CSRF defense: a write must carry one of these Content-Types, none of which an HTML form can
 * forge (a form is limited to x-www-form-urlencoded, multipart/form-data, text/plain). json is
 * the API default; gzip and octet-stream are the hot-update web push's artifact transport
 * (src/hmr). A write with NO Content-Type and an empty body is let through — a form always
 * sends a form-type one.
 */
const ALLOWED_WRITE_CONTENT_TYPES = [
  "application/json",
  "application/gzip",
  "application/octet-stream",
];

/**
 * A workflow's own handler (`…/workflows/:id/api/*`) takes any body — an upload, a form of a
 * program it relays — so there the content type cannot be the defense. What stands in for it
 * is the browser's own account of where the request came from, which a page cannot forge:
 * `Sec-Fetch-Site`, and `Origin` against `Host` for a browser that sends no fetch metadata.
 * A request with neither is not a browser's, and carries no ambient cookie to ride on.
 */
const WORKFLOW_API = /^\/api\/projects\/[^/]+\/agents\/[^/]+\/workflows\/[^/]+\/api(\/|$)/;

function fromThisOrigin(header: (name: string) => string | undefined): boolean {
  const site = header("sec-fetch-site");
  if (site !== undefined) return site === "same-origin";
  const origin = header("origin");
  if (origin === undefined) return true;
  try {
    return new URL(origin).host === header("host");
  } catch {
    return false;
  }
}

const crossOrigin = () =>
  new HttpError(
    403,
    "cross_origin_write",
    "A request to a workflow's handler must come from this app's own pages.",
  );

export const jsonOnlyWrites: MiddlewareHandler = async (c, next) => {
  // A workflow's handler answers every method, so its GET is whatever the workflow made it
  // — not the read every other route's GET is. A `SameSite=Lax` cookie rides along on a
  // cross-site top-level navigation, so `window.open` on another site would otherwise run
  // that handler as the signed-in user; the browser's own account of where the request came
  // from is what settles it, on every method rather than only on writes.
  if (!WRITE_METHODS.has(c.req.method) && WORKFLOW_API.test(c.req.path)) {
    if (!fromThisOrigin((name) => c.req.header(name))) throw crossOrigin();
  }
  if (WRITE_METHODS.has(c.req.method)) {
    const contentType = c.req.header("content-type")?.toLowerCase();
    const forgeable =
      contentType !== undefined &&
      contentType !== "" &&
      !ALLOWED_WRITE_CONTENT_TYPES.some((t) => contentType.startsWith(t));
    if (forgeable && WORKFLOW_API.test(c.req.path)) {
      if (!fromThisOrigin((name) => c.req.header(name))) throw crossOrigin();
    } else if (forgeable) {
      throw new HttpError(
        415,
        "unsupported_media_type",
        "Write requests only accept application/json (or, for the hot-update web push, a gzip artifact).",
      );
    }
  }
  await next();
};