All files / src/app/api/patient/app-devices route.ts

56.52% Statements 26/46
65.38% Branches 17/26
50% Functions 1/2
56.81% Lines 25/44

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                          2x                                                                           7x 7x 6x     6x 6x       6x 7x 7x               6x 2x 2x         2x                             4x 4x         4x 2x               2x           2x 2x 2x         2x 1x               1x 1x            
import { NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { requireAppToken, isAppAuthError } from "@/lib/app-auth";
import {
  cleanDeviceName,
  DEVICE_ID,
  listConnections,
  registerConnection,
} from "@/lib/app-connections";
import { completePairing, getPairing } from "@/lib/app-pairing";
import { ACCOUNT_CLIENT_ID } from "@/lib/app-accounts";
import { sessionUsername } from "@/lib/patient/session-username";
 
export const dynamic = "force-dynamic";
 
/**
 * GET /api/patient/app-devices
 *
 * The phones this patient connected (#473), for the patient screen's list
 * with Disconnect. A PATIENT session, own login only.
 */
export async function GET() {
  const auth = await requireAuth(["PATIENT"]);
  if (isAuthError(auth)) return auth;
  const username = await sessionUsername();
  if (!username) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  try {
    const devices = await listConnections(username);
    return NextResponse.json({ devices });
  } catch (err) {
    console.error("GET /api/patient/app-devices:", err);
    return NextResponse.json({ error: "Neo4j unavailable" }, { status: 502 });
  }
}
 
/**
 * POST /api/patient/app-devices
 *
 * Called by the Klarbefund app once it holds a token (ADR-049): registers the
 * phone under the pairing it scanned. The token must be the app's, and the
 * pairing must have been started by the same login the token names, so a QR
 * code from someone else's screen cannot bind your phone to their record, or
 * theirs to yours.
 *
 * Body: `{ pairingId, deviceId, deviceName }`, deviceId a UUID v4 the app
 * generated once. A token from a password sign-in (`klarbefund-account`,
 * ADR-054) needs no pairingId.
 */
export async function POST(request: Request) {
  const auth = await requireAppToken(request, { device: false });
  if (isAppAuthError(auth)) return auth;
  const { username } = auth.app;
 
  let body: { pairingId?: unknown; deviceId?: unknown; deviceName?: unknown };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Body must be JSON" }, { status: 400 });
  }
  const pairingId = typeof body.pairingId === "string" ? body.pairingId : "";
  const deviceId = typeof body.deviceId === "string" ? body.deviceId : "";
  Iif (!DEVICE_ID.test(deviceId)) {
    return NextResponse.json(
      { error: "deviceId must be a UUID v4" },
      { status: 400 },
    );
  }
  // A password sign-in is a full sign-in, as on the website: the phone needs
  // no QR code to register under its own login (ADR-054).
  if (!pairingId && auth.app.client === ACCOUNT_CLIENT_ID) {
    try {
      const connection = await registerConnection({
        deviceId,
        deviceName: cleanDeviceName(body.deviceName),
        username,
      });
      return connection
        ? NextResponse.json({ connection }, { status: 201 })
        : NextResponse.json(
            {
              error: "Conflict",
              reason: "this device id belongs to another login",
            },
            { status: 409 },
          );
    } catch (err) {
      console.error("POST /api/patient/app-devices:", err);
      return NextResponse.json({ error: "Neo4j unavailable" }, { status: 502 });
    }
  }
  let pairing;
  try {
    pairing = await getPairing(pairingId, username);
  } catch (err) {
    console.error("POST /api/patient/app-devices:", err);
    return NextResponse.json({ error: "Neo4j unavailable" }, { status: 502 });
  }
  if (!pairing) {
    return NextResponse.json(
      {
        error: "Forbidden",
        reason: "no pairing of this login matches; scan a new QR code",
      },
      { status: 403 },
    );
  }
  Iif (pairing.deviceId && pairing.deviceId !== deviceId) {
    return NextResponse.json(
      { error: "Conflict", reason: "this QR code already connected a phone" },
      { status: 409 },
    );
  }
  const deviceName = cleanDeviceName(body.deviceName);
  try {
    const connection = await registerConnection({
      deviceId,
      deviceName,
      username,
    });
    if (!connection) {
      return NextResponse.json(
        {
          error: "Conflict",
          reason: "this device id belongs to another login",
        },
        { status: 409 },
      );
    }
    await completePairing(pairing.id, username, deviceId, deviceName);
    return NextResponse.json({ connection }, { status: 201 });
  } catch (err) {
    console.error("POST /api/patient/app-devices:", err);
    return NextResponse.json({ error: "Neo4j unavailable" }, { status: 502 });
  }
}