All files / src/app/api/app-accounts route.ts

91.89% Statements 34/37
77.27% Branches 17/22
66.66% Functions 2/3
94.44% Lines 34/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148                                                2x     2x                               13x 13x       13x 52x 13x 13x 13x 13x 13x 1x                 12x 1x                 11x 11x             1x 1x             10x             10x 10x 10x         10x 1x         9x 9x 7x             2x 2x     2x 2x   2x     2x           7x                        
import { NextResponse } from "next/server";
import {
  AttestError,
  checkChallenge,
  clientData,
  verifyAttestation,
} from "@/lib/app-attest";
import {
  ACCOUNT_CLIENT_ID,
  AccountError,
  createKeycloakUser,
  createSandboxRecord,
  deleteSandboxRecord,
  newCredentials,
  sandboxPatientId,
} from "@/lib/app-accounts";
import {
  cleanDeviceName,
  DEVICE_ID,
  registerConnection,
} from "@/lib/app-connections";
import { ehdsOrigin } from "@/lib/app-pairing";
import { accountLimiter, clientAddress } from "@/lib/account-rate-limit";
 
export const dynamic = "force-dynamic";
 
const keycloakPublicUrl =
  process.env.KEYCLOAK_PUBLIC_URL ?? "http://localhost:8080/realms/edcv";
 
/**
 * POST /api/app-accounts
 *
 * Creates a sandbox account for the Klarbefund app (ADR-054): a Keycloak
 * login with a generated password, an empty record of its own, and this phone
 * already connected to it. Answers without a session, and only to a request
 * Apple attests comes from the genuine app on a real device.
 *
 * Body: `{ challenge, keyId, attestation, deviceId, deviceName }`, the
 * attestation over SHA-256 of `challenge|deviceId`. The password is in the
 * answer once and nowhere else on the hub.
 */
export async function POST(request: Request) {
  let body: Record<string, unknown>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Body must be JSON" }, { status: 400 });
  }
  const text = (key: string) =>
    typeof body[key] === "string" ? (body[key] as string) : "";
  const challenge = text("challenge");
  const keyId = text("keyId");
  const attestation = text("attestation");
  const deviceId = text("deviceId");
  if (!challenge || !keyId || !attestation || !DEVICE_ID.test(deviceId)) {
    return NextResponse.json(
      {
        error: "Bad request",
        reason:
          "challenge, keyId, attestation and a UUID v4 deviceId are required",
      },
      { status: 400 },
    );
  }
  if (!checkChallenge(challenge)) {
    return NextResponse.json(
      {
        error: "Unauthorized",
        reason: "the challenge is not the hub's, or it expired",
      },
      { status: 401 },
    );
  }
  let attested;
  try {
    attested = verifyAttestation({
      keyId,
      attestation,
      clientData: clientData(challenge, deviceId),
    });
  } catch (err) {
    const reason =
      err instanceof AttestError ? err.message : "not an attestation";
    return NextResponse.json(
      { error: "Unauthorized", reason },
      { status: 401 },
    );
  }
 
  // Behind the attestation, a second line: per address and in all, per hour.
  Iif (!accountLimiter.allow(clientAddress(request))) {
    return NextResponse.json(
      { error: "Too many accounts, try again later" },
      { status: 429 },
    );
  }
 
  const credentials = newCredentials();
  try {
    const fresh = await createSandboxRecord({
      username: credentials.username,
      keyId,
      environment: attested.environment,
    });
    if (!fresh) {
      return NextResponse.json(
        { error: "Conflict", reason: "this key already created an account" },
        { status: 409 },
      );
    }
    try {
      await createKeycloakUser(credentials);
      await registerConnection({
        deviceId,
        deviceName: cleanDeviceName(body.deviceName),
        username: credentials.username,
      });
    } catch (err) {
      // No half-made account: the record goes, the key stays spent.
      await deleteSandboxRecord(credentials.username).catch(() => undefined);
      throw err;
    }
  } catch (err) {
    console.error("POST /api/app-accounts:", err);
    const status = err instanceof AccountError ? err.status : 502;
    const reason =
      err instanceof AccountError
        ? err.message
        : "the hub could not create the account";
    return NextResponse.json(
      { error: "Account not created", reason },
      { status },
    );
  }
 
  return NextResponse.json(
    {
      username: credentials.username,
      password: credentials.password,
      patientId: sandboxPatientId(credentials.username),
      ehds: ehdsOrigin(request),
      issuer: keycloakPublicUrl,
      client: ACCOUNT_CLIENT_ID,
    },
    { status: 201, headers: { "Cache-Control": "no-store" } },
  );
}