All files / src/lib/edc participants.ts

100% Statements 24/24
96.07% Branches 49/51
100% Functions 9/9
100% Lines 23/23

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 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185                                      13x                                                   106x                         102x 69x       14x         633x       107x 107x 107x 107x   107x 107x                                         4x 3x                                                   18x 18x 18x   18x 18x               18x                                                                               12x 9x 14x      
import { edcClient, EDC_CONTEXT } from "@/lib/edc";
import { PROVISIONING_STALL_MS, type VpaSummary } from "@/lib/provisioning";
import { holdsMembership } from "@/lib/edc/provision";
 
/**
 * Participants as the hub sees them on EDC 1.0: control plane contexts
 * (ADR-078). The tenant, participant profile and VPA of CFM are gone; the
 * routes still answer in the tenant shape the onboarding, settings and admin
 * pages read, with the context id as the tenant id.
 */
 
/**
 * Approved fictional participants, display names by DID slug. The seeded
 * five carry no properties on their context, so their names come from here;
 * a participant onboarded through the hub carries its own.
 */
const SLUG_DISPLAY_NAMES: Record<
  string,
  { displayName: string; org: string; role: string }
> = {
  "alpha-klinik": {
    displayName: "AlphaKlinik Berlin",
    org: "AlphaKlinik Berlin",
    role: "DATA_HOLDER",
  },
  lmc: {
    displayName: "Limburg Medical Centre",
    org: "Limburg Medical Centre",
    role: "DATA_HOLDER",
  },
  pharmaco: {
    displayName: "PharmaCo Research AG",
    org: "PharmaCo Research AG",
    role: "DATA_USER",
  },
  medreg: { displayName: "MedReg DE", org: "MedReg DE", role: "HDAB" },
  irs: {
    displayName: "Institut de Recherche Santé",
    org: "Institut de Recherche Santé",
    role: "HDAB",
  },
};
 
/** The last segment of a did:web ("did:web:identityhub%3A7083:lmc" is "lmc"). */
function didSlug(did: string): string {
  return decodeURIComponent(did).split(":").pop()?.toLowerCase() ?? "";
}
 
export interface HubContext {
  "@id": string;
  identity?: string;
  participantId?: string;
  state?: string;
  properties?: Record<string, unknown>;
  [key: string]: unknown;
}
 
export async function listContexts(): Promise<HubContext[]> {
  const all = await edcClient.management<HubContext[]>("/v5/participants");
  return Array.isArray(all) ? all : [];
}
 
export function getContext(id: string): Promise<HubContext> {
  return edcClient.management<HubContext>(
    `/v5/participants/${encodeURIComponent(id)}`,
  );
}
 
const str = (v: unknown) => (typeof v === "string" && v ? v : undefined);
 
/** Name, organisation and role: the context's own, else the seeded five's. */
export function contextNames(ctx: HubContext) {
  const did = ctx.identity ?? ctx.participantId ?? "";
  const slug = did ? didSlug(did) : "";
  const known = SLUG_DISPLAY_NAMES[slug];
  const p = ctx.properties ?? {};
  const displayName =
    str(p.displayName) || known?.displayName || slug || ctx["@id"].slice(0, 12);
  return {
    did,
    slug,
    displayName,
    organization: str(p.organization) || known?.org || displayName,
    role: str(p.role) || known?.role || "",
    ehdsParticipantType:
      str(p.ehdsParticipantType) || str(p.role) || known?.role || "",
    registeredAt: str(p.registeredAt),
  };
}
 
/**
 * Replaces the context's properties with `properties` merged over them. 1.0
 * replaces the whole map on PUT (an update without it empties it), so the
 * current one is read first.
 */
export async function updateContextProperties(
  id: string,
  properties: Record<string, string>,
): Promise<void> {
  const ctx = await getContext(id);
  await edcClient.management(
    `/v5/participants/${encodeURIComponent(id)}`,
    "PUT",
    {
      "@context": [EDC_CONTEXT],
      "@type": "ParticipantContext",
      "@id": ctx["@id"],
      identity: ctx.identity,
      state: ctx.state,
      properties: { ...(ctx.properties ?? {}), ...properties },
    },
  );
}
 
/**
 * One context in the tenant shape of /api/participants/me. Provisioning is
 * synchronous now, so a context that exists has its DID and keys; what can
 * still be outstanding is the MembershipCredential, which the issuer delivers
 * over DCP. Until it has, the card says provisioning, and after
 * PROVISIONING_STALL_MS it says stalled, with the reason.
 */
export function toTenantView(
  ctx: HubContext,
  holdsCredential: boolean,
  now: number = Date.now(),
) {
  const n = contextNames(ctx);
  const since = n.registeredAt ? Date.parse(n.registeredAt) : NaN;
  const waiting = !holdsCredential;
  const stalled =
    waiting && (Number.isNaN(since) || now - since > PROVISIONING_STALL_MS);
  const vpaSummary: VpaSummary = {
    total: 1,
    pending: waiting ? 1 : 0,
    pendingTypes: waiting ? ["MembershipCredential"] : [],
    oldestPendingSince:
      waiting && !Number.isNaN(since) ? new Date(since).toISOString() : null,
    stalled,
  };
  return {
    id: ctx["@id"],
    version: 0,
    properties: {
      displayName: n.displayName,
      organization: n.organization,
      role: n.role,
      ehdsParticipantType: n.ehdsParticipantType,
      ...(n.registeredAt ? { registeredAt: n.registeredAt } : {}),
    },
    participantProfiles: [
      {
        id: ctx["@id"],
        participantContextId: ctx["@id"],
        identifier: n.did,
        did: n.did,
        state: ctx.state,
      },
    ],
    vpaSummary,
    provisioningComplete: holdsCredential,
    provisioningFailed: false,
    provisioningStalled: stalled,
    ...(stalled
      ? {
          stalledReason:
            `The participant context, its DID and keys exist, but the issuer ` +
            `has not delivered its MembershipCredential` +
            (Number.isNaN(since)
              ? ""
              : ` since ${new Date(since).toISOString()}`) +
            `. The IssuerService's log names the cause; without the credential ` +
            `no other participant will negotiate with it.`,
        }
      : {}),
  };
}
 
/** Every context in the tenant shape, each with whether it holds its credential. */
export async function listTenantViews() {
  const contexts = await listContexts();
  return Promise.all(
    contexts.map(async (c) => toTenantView(c, await holdsMembership(c["@id"]))),
  );
}