~ knotless Search/
↑↓ move↵ open⇧↵ all results

socialweb.computer/socialweb-computer-kcp

socialweb.computer: a compute market on atproto (kcp)

1 collaborator
0
0
428 lines · 15.3 KB Raw History
import { Hono } from "@hono/hono";
import type { Context } from "@hono/hono";
import { Command } from "@publicdomainrelay/cli-args-env";
import { createLogger } from "@publicdomainrelay/logger";
import { createServe } from "@publicdomainrelay/serve";
import cliArgsEnv from "./cli-args-env.json" with { type: "json" };
import { Identity, IdentityError } from "./identity.ts";

const OAUTH_QR_NSID = "com.fedfork.atprotoOauthQR";
const NONCE_HEADER = "x-oauth-qr-nonce";
const CLIENT_IP_HEADER = "x-qr-client-ip";
const GENERIC_UNAUTHORIZED = "invalid service auth token";
const GENERIC_UNVERIFIED = "The session could not be verified with the account's PDS. Sign in again from a new QR code.";

interface OAuthSessionData {
  accessJwt: string;
  refreshJwt: string;
  userDid: string;
  handle: string;
  pds: string;
  dpopPublicJwk: Record<string, string>;
  dpopPrivateJwk: Record<string, string>;
  scope?: string;
}

type LinkState = "open" | "transferred" | "collected" | "superseded";

interface LinkEntry {
  issuedAt: number;
  expiresAt: number;
  state: LinkState;
  transferredAt?: number;
  sessionDid?: string;
}

interface SessionEntry {
  session: OAuthSessionData;
  verifiedDid: string;
}

interface LinkProblem {
  status: 404 | 410;
  error: string;
  message: string;
}

const MAX_LINK_TTL_S = 300;
const COLLECT_TTL_MS = 5 * 60 * 1000;
const TOMBSTONE_TTL_MS = 24 * 60 * 60 * 1000;
const UNUSED_RETENTION_MS = 60 * 60 * 1000;
const MAX_OPEN_PER_DID = 4;
const JWT_MAX_LIFETIME_S = 120;
const JWT_SKEW_S = 30;
const NONCE_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
const LINK_PREFIX = "oauthQrLink";
const SESSION_PREFIX = "oauthQrSession";
const OPEN_PREFIX = "oauthQrOpen";
const JTI_PREFIX = "oauthQrJti";
const LEGACY_PREFIX = ["oauthQr"];

let linkTtlMs = MAX_LINK_TTL_S * 1000;

class Limiter {
  #limit: number;
  #windowMs: number;
  #window = 0;
  #counts = new Map<string, number>();

  constructor(limit: number, windowMs: number) {
    this.#limit = limit;
    this.#windowMs = windowMs;
  }

  allow(key: string, now: number): boolean {
    const w = Math.floor(now / this.#windowMs);
    if (w !== this.#window || this.#counts.size > 100_000) {
      this.#window = w;
      this.#counts.clear();
    }
    const n = (this.#counts.get(key) ?? 0) + 1;
    this.#counts.set(key, n);
    return n <= this.#limit;
  }
}

const MINUTE = 60 * 1000;
const MAX_VERIFY_PER_SOURCE = 2;
const limits = {
  pollPerDid: new Limiter(120, MINUTE),
  pollGlobal: new Limiter(6000, MINUTE),
  registerPerDid: new Limiter(12, MINUTE),
  registerPerSource: new Limiter(60, MINUTE),
  registerGlobal: new Limiter(600, MINUTE),
  postPerSource: new Limiter(30, MINUTE),
  postGlobal: new Limiter(600, MINUTE),
};
const verifying = new Map<string, number>();

const logger = createLogger({ serviceName: "oauth-qr" });

const kvPath = Deno.env.get("KV_PATH") || undefined;
let kv: Deno.Kv;

async function purgeLegacyEntries(k: Deno.Kv): Promise<void> {
  for await (const e of k.list({ prefix: LEGACY_PREFIX })) await k.delete(e.key);
}

async function getKv(): Promise<Deno.Kv> {
  if (!kv) {
    kv = await Deno.openKv(kvPath);
    await purgeLegacyEntries(kv);
  }
  return kv;
}

function linkKey(cliDid: string, nonce: string): Deno.KvKey {
  return [LINK_PREFIX, cliDid, nonce];
}

function sessionKey(cliDid: string, nonce: string): Deno.KvKey {
  return [SESSION_PREFIX, cliDid, nonce];
}

function openKey(cliDid: string, nonce: string): Deno.KvKey {
  return [OPEN_PREFIX, cliDid, nonce];
}

function retention(entry: LinkEntry, now: number): number {
  const keep = entry.state === "open" || entry.state === "superseded" ? UNUSED_RETENTION_MS : TOMBSTONE_TTL_MS;
  return Math.max(entry.expiresAt + keep - now, 1000);
}

const USED: LinkProblem = {
  status: 410,
  error: "LinkUsed",
  message: "This sign-in link was already used. Ask the device for a new QR code.",
};
const EXPIRED: LinkProblem = {
  status: 410,
  error: "LinkExpired",
  message: "This sign-in link expired. Ask the device for a new QR code.",
};
const UNKNOWN: LinkProblem = {
  status: 404,
  error: "LinkUnknown",
  message: "This sign-in link is not active: it expired or was never issued. Ask the device for a new QR code.",
};
const SUPERSEDED: LinkProblem = {
  status: 410,
  error: "LinkSuperseded",
  message: "The device has issued a newer sign-in link. Scan its current QR code.",
};

function linkProblem(entry: LinkEntry | null, now: number): LinkProblem | null {
  if (!entry) return UNKNOWN;
  if (entry.state === "superseded") return SUPERSEDED;
  if (entry.state !== "open") return USED;
  if (now >= entry.expiresAt) return EXPIRED;
  return null;
}

function problemReply(c: Context, p: LinkProblem) {
  return c.json({ error: p.error, message: p.message }, p.status);
}

function isLoopbackAddress(ip: string): boolean {
  return ip === "::1" || ip === "localhost" || /^127\./.test(ip) || /^::ffff:127\./i.test(ip);
}

function sourceKey(ip: string): string {
  const addr = ip.trim().replace(/^\[|\]$/g, "").toLowerCase();
  if (!addr.includes(":") || /^::ffff:\d+\.\d+\.\d+\.\d+$/.test(addr)) return addr.replace(/^::ffff:/, "");
  const [head, tail = ""] = addr.split("::");
  const h = head ? head.split(":") : [];
  const t = tail ? tail.split(":") : [];
  const words = [...h, ...Array(Math.max(8 - h.length - t.length, 0)).fill("0"), ...t];
  return words.slice(0, 4).map((w) => parseInt(w || "0", 16).toString(16)).join(":") + "::/64";
}

function clientSource(c: Context): string {
  const info = c.env as { remoteAddr?: { hostname?: string } } | undefined;
  const peer = info?.remoteAddr?.hostname ?? "";
  if (peer && !isLoopbackAddress(peer)) return sourceKey(peer);
  const edge = c.req.header(CLIENT_IP_HEADER) ?? "";
  return /^[0-9a-fA-F:.]{2,45}$/.test(edge) ? sourceKey(edge) : "edge-unknown";
}

async function registerLink(k: Deno.Kv, cliDid: string, nonce: string, now: number): Promise<boolean> {
  const open: { key: Deno.KvKey; issuedAt: number }[] = [];
  for await (const e of k.list<number>({ prefix: [OPEN_PREFIX, cliDid] })) {
    if (now - e.value >= linkTtlMs) await k.delete(e.key);
    else open.push({ key: e.key, issuedAt: e.value });
  }
  open.sort((a, b) => a.issuedAt - b.issuedAt);
  while (open.length >= MAX_OPEN_PER_DID) {
    const oldest = open.shift()!;
    const oldNonce = oldest.key[2] as string;
    const res = await k.get<LinkEntry>(linkKey(cliDid, oldNonce));
    const op = k.atomic().check(res).delete(oldest.key);
    if (res.value?.state === "open") {
      const sup: LinkEntry = { ...res.value, state: "superseded" };
      op.set(res.key, sup, { expireIn: retention(sup, now) });
    }
    await op.commit();
  }
  const key = linkKey(cliDid, nonce);
  const issued: LinkEntry = { issuedAt: now, expiresAt: now + linkTtlMs, state: "open" };
  const res = await k.atomic()
    .check({ key, versionstamp: null })
    .set(key, issued, { expireIn: retention(issued, now) })
    .set(openKey(cliDid, nonce), now, { expireIn: linkTtlMs })
    .commit();
  return res.ok;
}

const app = new Hono();

app.post(`/xrpc/${OAUTH_QR_NSID}`, async (c) => {
  const started = Date.now();
  const source = clientSource(c);
  if (!limits.postPerSource.allow(source, started) || !limits.postGlobal.allow("all", started)) {
    return c.json({ error: "RateLimited", message: "too many requests; try again in a minute" }, 429);
  }
  let body: Record<string, unknown>;
  try {
    body = await c.req.json();
  } catch {
    return c.json({ error: "InvalidRequest", message: "invalid JSON" }, 400);
  }
  if (!body || typeof body !== "object") return c.json({ error: "InvalidRequest", message: "invalid JSON" }, 400);

  const str = (v: unknown) => (typeof v === "string" && v ? v : undefined);
  const jwk = (v: unknown) => (v && typeof v === "object" && !Array.isArray(v) ? v as Record<string, string> : undefined);
  const cliDid = str(body.cliDid);
  const nonce = str(body.nonce);
  const accessJwt = str(body.accessJwt);
  const refreshJwt = str(body.refreshJwt);
  const userDid = str(body.userDid);
  const handle = str(body.handle);
  const pds = str(body.pds);
  const dpopPublicJwk = jwk(body.dpopPublicJwk);
  const dpopPrivateJwk = jwk(body.dpopPrivateJwk);
  const scope = str(body.scope);

  if (!cliDid?.startsWith("did:") || !nonce) {
    return c.json({ error: "InvalidRequest", message: "missing cliDid or nonce" }, 400);
  }
  if (cliDid.length > 2048 || !NONCE_PATTERN.test(nonce)) {
    return c.json({ error: "InvalidRequest", message: "malformed cliDid or nonce" }, 400);
  }

  const k = await getKv();
  const key = linkKey(cliDid, nonce);
  const res = await k.get<LinkEntry>(key);
  const problem = linkProblem(res.value, Date.now());
  if (problem) return problemReply(c, problem);
  const entry = res.value as LinkEntry;

  const fields = [body.accessJwt, body.refreshJwt, body.userDid, body.handle, body.pds, body.dpopPublicJwk, body.dpopPrivateJwk];
  if (fields.every((v) => v === undefined)) {
    return c.json({ ok: true, status: "waiting", expiresAt: new Date(entry.expiresAt).toISOString() });
  }
  if (!(accessJwt && refreshJwt && userDid && handle && pds && dpopPublicJwk && dpopPrivateJwk)) {
    return c.json({ error: "InvalidRequest", message: "incomplete session" }, 400);
  }
  if (accessJwt.length > 8192 || refreshJwt.length > 8192 || userDid.length > 256 || pds.length > 512) {
    return c.json({ error: "InvalidRequest", message: "oversized session field" }, 400);
  }

  const busy = verifying.get(source) ?? 0;
  if (busy >= MAX_VERIFY_PER_SOURCE) {
    return c.json({ error: "RateLimited", message: "a transfer from this address is already being checked" }, 429);
  }
  verifying.set(source, busy + 1);
  let verified;
  try {
    verified = await identity.verifySession({ userDid, pds, accessJwt, dpopPublicJwk, dpopPrivateJwk });
  } catch (err: unknown) {
    logger.info("session unverified", { reason: err instanceof IdentityError ? err.message : "error" });
    return c.json({ error: "SessionUnverified", message: GENERIC_UNVERIFIED }, 422);
  } finally {
    const left = (verifying.get(source) ?? 1) - 1;
    if (left <= 0) verifying.delete(source);
    else verifying.set(source, left);
  }

  const now = Date.now();
  if (now >= entry.expiresAt) return problemReply(c, EXPIRED);
  const session: OAuthSessionData = {
    accessJwt,
    refreshJwt,
    userDid,
    handle: verified.handle,
    pds,
    dpopPublicJwk,
    dpopPrivateJwk,
    ...(scope ? { scope } : {}),
  };
  const next: LinkEntry = { ...entry, state: "transferred", transferredAt: now, sessionDid: verified.did };
  const committed = await k.atomic()
    .check(res)
    .set(key, next, { expireIn: retention(next, now) })
    .set(sessionKey(cliDid, nonce), { session, verifiedDid: verified.did } satisfies SessionEntry, { expireIn: COLLECT_TTL_MS })
    .delete(openKey(cliDid, nonce))
    .commit();
  if (!committed.ok) {
    const again = await k.get<LinkEntry>(key);
    return problemReply(c, linkProblem(again.value, now) ?? USED);
  }
  return c.json({ ok: true, did: verified.did });
});

app.get(`/xrpc/${OAUTH_QR_NSID}`, async (c) => {
  const authHeader = c.req.header("authorization");
  if (!authHeader) {
    return c.json({ error: "Unauthorized", message: "missing Authorization header" }, 401);
  }
  const match = /^Bearer (.+)$/.exec(authHeader.trim());
  if (!match) {
    return c.json({ error: "Unauthorized", message: "malformed Authorization header" }, 401);
  }

  const nowS = Math.floor(Date.now() / 1000);

  let claims;
  try {
    claims = await identity.verifyServiceAuth(match[1], {
      aud: serviceDid,
      lxm: OAUTH_QR_NSID,
      maxLifetimeS: JWT_MAX_LIFETIME_S,
      skewS: JWT_SKEW_S,
    }, nowS);
  } catch {
    return c.json({ error: "Unauthorized", message: GENERIC_UNAUTHORIZED }, 401);
  }
  const issuerDid = claims.iss;
  const polled = Date.now();
  if (!limits.pollPerDid.allow(issuerDid, polled) || !limits.pollGlobal.allow("all", polled)) {
    return c.json({ error: "RateLimited", message: "too many polls; slow down" }, 429);
  }

  const k = await getKv();
  const jtiKey = [JTI_PREFIX, issuerDid, claims.jti];
  const fresh = await k.atomic()
    .check({ key: jtiKey, versionstamp: null })
    .set(jtiKey, 1, { expireIn: Math.max((claims.exp - nowS + JWT_SKEW_S) * 1000, 1000) })
    .commit();
  if (!fresh.ok) return c.json({ error: "Unauthorized", message: GENERIC_UNAUTHORIZED }, 401);

  const nonce = c.req.header(NONCE_HEADER) ?? c.req.query("nonce") ?? "";
  if (!NONCE_PATTERN.test(nonce)) {
    return c.json({ error: "InvalidRequest", message: "missing or malformed nonce" }, 400);
  }

  const key = linkKey(issuerDid, nonce);
  const now = Date.now();
  const res = await k.get<LinkEntry>(key);
  if (!res.value) {
    if (
      !limits.registerPerDid.allow(issuerDid, now) || !limits.registerPerSource.allow(clientSource(c), now) ||
      !limits.registerGlobal.allow("all", now)
    ) {
      return c.json({ error: "RateLimited", message: "too many new links; slow down" }, 429);
    }
    await registerLink(k, issuerDid, nonce, now);
    return c.json({ error: "notReady" }, 404);
  }
  const entry = res.value;
  if (entry.state === "collected") return c.json({ error: "consumed" }, 404);
  if (entry.state === "superseded") return c.json({ error: "superseded" }, 404);
  if (entry.state === "open") return c.json({ error: now >= entry.expiresAt ? "expired" : "notReady" }, 404);

  const sres = await k.get<SessionEntry>(sessionKey(issuerDid, nonce));
  const done: LinkEntry = { ...entry, state: "collected" };
  const lapsed = !sres.value || now - (entry.transferredAt ?? 0) > COLLECT_TTL_MS;
  const committed = await k.atomic()
    .check(res)
    .check(sres)
    .set(key, done, { expireIn: retention(done, now) })
    .delete(sres.key)
    .commit();
  if (!committed.ok) return c.json({ error: "notReady" }, 404);
  if (lapsed || !sres.value) return c.json({ error: "expired" }, 404);
  return c.json({ ...sres.value.session, verifiedDid: sres.value.verifiedDid });
});

const { options } = await new Command(
  "CONFIG_PATH_HONO_BACKEND",
  cliArgsEnv,
  null,
).resolve();

const linkTtlSeconds = options.linkTtlSeconds as number;
if (!Number.isInteger(linkTtlSeconds) || linkTtlSeconds < 1 || linkTtlSeconds > MAX_LINK_TTL_S) {
  throw new Error(`link-ttl-seconds must be an integer from 1 to ${MAX_LINK_TTL_S}, got ${linkTtlSeconds}`);
}
linkTtlMs = linkTtlSeconds * 1000;
const bindAddr = options.addr as string;
const insecureLoopback = options.insecureLoopbackIdentity === true;
if (insecureLoopback && !isLoopbackAddress(bindAddr)) {
  throw new Error("insecure-loopback-identity is only allowed when addr is a loopback address");
}
const serviceDid = options.serviceDid as string;
if (!/^did:web:[a-z0-9.-]+$/.test(serviceDid)) throw new Error(`service-did must be a did:web, got ${serviceDid}`);
const networkOrigins = String(options.networkOrigins ?? "").split(",").map((o) => o.trim()).filter((o) => o !== "");
const identity = new Identity({ plcUrl: options.plcUrl as string, networkOrigins, insecureLoopback });

const serve = createServe({
  logger,
  tcp: {
    addr: bindAddr,
    port: options.port as number,
    certFile: options.tlsCertFile as string | undefined,
    keyFile: options.tlsKeyFile as string | undefined,
  },
  portFile: options.portFile as string | undefined,
});
serve.app.route("/", app as never);

function shutdown() {
  serve.shutdown();
  Deno.exit(0);
}
Deno.addSignalListener("SIGINT", shutdown);
Deno.addSignalListener("SIGTERM", shutdown);

await serve.beginServe();
logger.info("oauth-qr backend listening", { port: serve.tcpPort });