All files / src/app/credentials page.tsx

94.66% Statements 71/75
72.83% Branches 118/162
91.3% Functions 21/23
95.58% Lines 65/68

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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469                                                                                  82x 82x 82x 82x 82x 82x 82x 82x     82x 82x   82x 32x   29x   29x   29x         29x     29x 45x               45x                                                 29x     29x 29x   29x     29x 29x 29x   1x     82x 3x 3x 3x   3x 3x                 2x 1x   1x 1x 1x 1x 1x               1x                                                 1x 1x     1x   3x       82x 3x 2x 2x 2x       2x 2x 1x   1x 1x         2x       82x                                                                           93x                                       90x                                                                                                                                         82x 82x                       9x                                                                                                                                                                         44x                       3x 3x                                                
"use client";
 
import { fetchApi } from "@/lib/api";
import { useEffect, useState } from "react";
import PageIntro from "@/components/PageIntro";
import {
  ChevronDown,
  ChevronUp,
  Loader2,
  ShieldCheck,
  FileKey2,
  Send,
  Trash2,
} from "lucide-react";
 
interface VC {
  id: string;
  type: string;
  issuer: string;
  subject: string;
  issuanceDate: string;
  expirationDate?: string;
  status: string;
  claims: Record<string, string>;
}
 
interface ParticipantCtx {
  "@id": string;
  identity: string;
  state: string;
}
 
interface CredentialDef {
  id: string;
  credentialType: string;
  format: string;
  attestations: string[];
  validity: number;
}
 
export default function CredentialsPage() {
  const [credentials, setCredentials] = useState<VC[]>([]);
  const [participants, setParticipants] = useState<ParticipantCtx[]>([]);
  const [credentialDefs, setCredentialDefs] = useState<CredentialDef[]>([]);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState<string | null>(null);
  const [requesting, setRequesting] = useState(false);
  const [requestResult, setRequestResult] = useState<string | null>(null);
  const [removingId, setRemovingId] = useState<string | null>(null);
 
  // Request form
  const [reqParticipant, setReqParticipant] = useState("");
  const [reqType, setReqType] = useState("");
 
  useEffect(() => {
    Promise.all([
      fetchApi("/api/credentials").then((r) =>
        r.ok ? r.json() : { credentials: [] },
      ),
      fetchApi("/api/participants").then((r) => (r.ok ? r.json() : [])),
      fetchApi("/api/credentials/definitions").then((r) =>
        r.ok ? r.json() : { definitions: [] },
      ),
    ])
      .then(([creds, ctx, defs]) => {
        // API returns { credentials: [...] } with Neo4j field names — map to UI shape
        const raw: any[] = Array.isArray(creds)
          ? creds
          : creds.credentials || [];
        setCredentials(
          raw.map((c: any) => ({
            id: c.credentialId ?? c.id ?? "",
            type: c.credentialType ?? c.type ?? "",
            issuer: c.issuerDid ?? c.issuer ?? "",
            subject: c.subjectDid ?? c.subject ?? "",
            issuanceDate: c.issuedAt ?? c.issuanceDate ?? "",
            expirationDate: c.expiresAt ?? c.expirationDate,
            status: (c.status ?? "unknown").replace(/^\w/, (ch: string) =>
              ch.toUpperCase(),
            ),
            claims: {
              ...(c.holderName ? { holder: c.holderName } : {}),
              ...(c.holderType ? { type: c.holderType } : {}),
              ...(c.participantRole ? { role: c.participantRole } : {}),
              ...(c.membership ? { membership: c.membership } : {}),
              ...(c.membershipType ? { membershipType: c.membershipType } : {}),
              ...(c.jurisdiction ? { jurisdiction: c.jurisdiction } : {}),
              ...(c.ehdsArticle ? { ehdsArticle: c.ehdsArticle } : {}),
              ...(c.purpose ? { purpose: c.purpose } : {}),
              ...(c.datasetId ? { dataset: c.datasetId } : {}),
              ...(c.completeness != null
                ? { completeness: String(c.completeness) }
                : {}),
              ...(c.conformance != null
                ? { conformance: String(c.conformance) }
                : {}),
              ...(c.timeliness != null
                ? { timeliness: String(c.timeliness) }
                : {}),
            },
          })),
        );
        // API returns flat array [...] — handle both array and { participants: [...] }
        const list: ParticipantCtx[] = Array.isArray(ctx)
          ? ctx
          : ctx.participants || [];
        setParticipants(list);
        if (list.length > 0) setReqParticipant(list[0]["@id"]);
        // Load credential definitions from IssuerService
        const defList: CredentialDef[] = Array.isArray(defs)
          ? defs
          : defs.definitions || [];
        setCredentialDefs(defList);
        if (defList.length > 0) setReqType(defList[0].credentialType);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);
 
  const handleRequest = async () => {
    Iif (!reqParticipant) return;
    setRequesting(true);
    setRequestResult(null);
 
    try {
      const res = await fetchApi("/api/credentials/request", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          participantContextId: reqParticipant,
          credentialType: reqType,
        }),
      });
 
      if (res.ok) {
        setRequestResult("Credential request submitted successfully");
        // Refresh credentials list
        const updated = await fetchApi("/api/credentials");
        const data = await updated.json();
        const raw: any[] = Array.isArray(data) ? data : data.credentials || [];
        setCredentials(
          raw.map((c: any) => ({
            id: c.credentialId ?? c.id ?? "",
            type: c.credentialType ?? c.type ?? "",
            issuer: c.issuerDid ?? c.issuer ?? "",
            subject: c.subjectDid ?? c.subject ?? "",
            issuanceDate: c.issuedAt ?? c.issuanceDate ?? "",
            expirationDate: c.expiresAt ?? c.expirationDate,
            status: (c.status ?? "unknown").replace(/^\w/, (ch: string) =>
              ch.toUpperCase(),
            ),
            claims: {
              ...(c.holderName ? { holder: c.holderName } : {}),
              ...(c.holderType ? { type: c.holderType } : {}),
              ...(c.participantRole ? { role: c.participantRole } : {}),
              ...(c.membership ? { membership: c.membership } : {}),
              ...(c.membershipType ? { membershipType: c.membershipType } : {}),
              ...(c.jurisdiction ? { jurisdiction: c.jurisdiction } : {}),
              ...(c.ehdsArticle ? { ehdsArticle: c.ehdsArticle } : {}),
              ...(c.purpose ? { purpose: c.purpose } : {}),
              ...(c.datasetId ? { dataset: c.datasetId } : {}),
              ...(c.completeness != null
                ? { completeness: String(c.completeness) }
                : {}),
              ...(c.conformance != null
                ? { conformance: String(c.conformance) }
                : {}),
              ...(c.timeliness != null
                ? { timeliness: String(c.timeliness) }
                : {}),
            },
          })),
        );
      } else {
        const err = await res.json();
        setRequestResult(`Error: ${err.error || "Request failed"}`);
      }
    } catch {
      setRequestResult("Error: Failed to submit request");
    } finally {
      setRequesting(false);
    }
  };
 
  const handleRemove = async (credentialId: string) => {
    if (!confirm("Remove this credential? This cannot be undone.")) return;
    setRemovingId(credentialId);
    try {
      const res = await fetchApi(
        `/api/credentials/${encodeURIComponent(credentialId)}`,
        { method: "DELETE" },
      );
      if (res.ok) {
        setCredentials((prev) => prev.filter((c) => c.id !== credentialId));
        Eif (expanded === credentialId) setExpanded(null);
      } else {
        const err = await res.json();
        alert(err.error || "Failed to remove credential");
      }
    } catch {
      alert("Failed to remove credential");
    } finally {
      setRemovingId(null);
    }
  };
 
  return (
    <div className="min-h-screen bg-[var(--bg)]">
      <div className="max-w-5xl mx-auto px-6 py-10">
        <PageIntro
          title="Verifiable Credentials"
          icon={FileKey2}
          description="Request and manage EHDS participant credentials issued via the IssuerService and stored in the IdentityHub. Verifiable Credentials prove identity, compliance status, and data-access authorisation within the dataspace."
          prevStep={{ href: "/compliance/tck", label: "Protocol TCK" }}
          nextStep={{ href: "/data/share", label: "Share Data" }}
          infoText="VCs follow the W3C Verifiable Credentials standard. They are cryptographically signed by the IssuerService and can be verified by any participant using the holder's DID:web identity."
          docLink={{ href: "/docs/architecture", label: "Architecture Docs" }}
        />
 
        {/* Request new credential */}
        <div className="border border-[var(--border)] rounded-xl p-5 mb-8">
          <div className="flex items-center gap-2 mb-2">
            <Send size={18} className="text-teal-800 dark:text-teal-300" />
            <h2 className="font-semibold text-sm">Request Credential</h2>
          </div>
          <p className="text-xs text-[var(--text-secondary)] mb-4">
            Request a Verifiable Credential (VC) from the IssuerService for a
            participant. VCs prove identity, compliance, and data-access
            authorization in the EHDS dataspace. They are stored in the
            participant&apos;s IdentityHub and presented during
            connector-to-connector negotiations.
          </p>
          <div className="grid sm:grid-cols-3 gap-3 items-end">
            <div>
              <label className="text-xs text-[var(--text-secondary)] mb-1 block">
                Participant Context
              </label>
              <select
                aria-label="Participant Context"
                value={reqParticipant}
                onChange={(e) => setReqParticipant(e.target.value)}
                className="w-full px-3 py-2 bg-[var(--surface-2)] border border-[var(--border-ui)] rounded text-sm"
              >
                {participants.map((p) => (
                  <option key={p["@id"]} value={p["@id"]}>
                    {p.identity?.replace("did:web:", "").replace(/%3A/g, ":") ||
                      p["@id"].slice(0, 16)}
                  </option>
                ))}
              </select>
            </div>
 
            <div>
              <label className="text-xs text-[var(--text-secondary)] mb-1 block">
                Credential Type
              </label>
              <select
                aria-label="Credential Type"
                value={reqType}
                onChange={(e) => setReqType(e.target.value)}
                className="w-full px-3 py-2 bg-[var(--surface-2)] border border-[var(--border-ui)] rounded text-sm"
              >
                {credentialDefs.length > 0 ? (
                  credentialDefs.map((d) => (
                    <option key={d.id} value={d.credentialType}>
                      {d.credentialType.replace(/([A-Z])/g, " $1").trim()}
                    </option>
                  ))
                ) : (
                  <>
                    <option value="EHDSParticipantCredential">
                      EHDS Participant Credential
                    </option>
                    <option value="DataProcessingPurposeCredential">
                      Data Processing Purpose Credential
                    </option>
                    <option value="DataQualityLabelCredential">
                      Data Quality Label Credential
                    </option>
                  </>
                )}
              </select>
            </div>
 
            <button
              onClick={handleRequest}
              disabled={requesting || !reqParticipant}
              className="flex items-center justify-center gap-2 px-4 py-2 bg-[var(--accent)] text-white dark:text-gray-900 rounded text-sm font-medium hover:bg-[var(--accent-hover)] disabled:opacity-50"
            >
              {requesting ? (
                <Loader2 size={14} className="animate-spin" />
              ) : (
                <FileKey2 size={14} />
              )}
              Request
            </button>
          </div>
 
          {requestResult && (
            <p
              className={`mt-3 text-xs ${
                requestResult.startsWith("Error")
                  ? "text-[var(--role-admin-text)]"
                  : "text-[var(--role-user-text)]"
              }`}
            >
              {requestResult}
            </p>
          )}
        </div>
 
        {/* Credential list */}
        {loading ? (
          <div className="flex items-center gap-2 text-[var(--text-secondary)]">
            <Loader2 size={16} className="animate-spin" />
            Loading credentials…
          </div>
        ) : credentials.length === 0 ? (
          <div className="text-center py-12">
            <ShieldCheck
              size={40}
              className="text-[var(--text-secondary)] mx-auto mb-4"
            />
            <p className="text-[var(--text-secondary)]">
              No credentials found in Neo4j
            </p>
            <p className="text-[var(--text-secondary)] text-xs mt-1">
              Register a participant and request credentials above
            </p>
          </div>
        ) : (
          <div className="grid gap-3">
            {credentials.map((vc) => {
              const isOpen = expanded === vc.id;
              return (
                <div
                  key={vc.id}
                  className={`border rounded-xl transition-colors ${
                    isOpen
                      ? "border-layer2 bg-[var(--surface)]/60"
                      : "border-[var(--border)] hover:border-layer2"
                  }`}
                >
                  <button
                    className="w-full text-left p-4"
                    aria-label={`${isOpen ? "Collapse" : "Expand"} ${vc.type}`}
                    onClick={() => setExpanded(isOpen ? null : vc.id)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <ShieldCheck
                          size={18}
                          className={
                            vc.status === "Active"
                              ? "text-[var(--role-user-text)]"
                              : "text-[var(--text-secondary)]"
                          }
                        />
                        <div>
                          <p className="font-medium text-sm text-[var(--text-primary)]">
                            {vc.type}
                          </p>
                          <p className="text-xs text-[var(--text-secondary)]">
                            {vc.subject?.slice(0, 40)}… · Issued:{" "}
                            {vc.issuanceDate?.split("T")[0]}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <span
                          className={`text-xs px-2 py-0.5 rounded-full ${
                            vc.status === "Active"
                              ? "bg-[var(--role-user-bg)] text-[var(--role-user-text)] border border-[var(--role-user-border)]"
                              : "bg-[var(--surface-2)] text-[var(--text-secondary)]"
                          }`}
                        >
                          {vc.status}
                        </span>
                        {isOpen ? (
                          <ChevronUp
                            size={16}
                            className="text-[var(--text-secondary)]"
                          />
                        ) : (
                          <ChevronDown
                            size={16}
                            className="text-[var(--text-secondary)]"
                          />
                        )}
                      </div>
                    </div>
                  </button>
 
                  {isOpen && (
                    <div className="px-4 pb-4 space-y-1.5 border-t border-[var(--border)] pt-3">
                      <div className="flex gap-3 text-xs">
                        <span className="text-[var(--text-secondary)] w-28">
                          ID
                        </span>
                        <span className="text-[var(--text-primary)] font-mono break-all">
                          {vc.id}
                        </span>
                      </div>
                      <div className="flex gap-3 text-xs">
                        <span className="text-[var(--text-secondary)] w-28">
                          Issuer
                        </span>
                        <span className="text-[var(--text-primary)] font-mono break-all">
                          {vc.issuer}
                        </span>
                      </div>
                      <div className="flex gap-3 text-xs">
                        <span className="text-[var(--text-secondary)] w-28">
                          Subject
                        </span>
                        <span className="text-[var(--text-primary)] font-mono break-all">
                          {vc.subject}
                        </span>
                      </div>
                      {vc.expirationDate && (
                        <div className="flex gap-3 text-xs">
                          <span className="text-[var(--text-secondary)] w-28">
                            Expires
                          </span>
                          <span className="text-[var(--text-primary)]">
                            {vc.expirationDate}
                          </span>
                        </div>
                      )}
                      {vc.claims &&
                        Object.entries(vc.claims).map(([k, v]) => (
                          <div key={k} className="flex gap-3 text-xs">
                            <span className="text-[var(--text-secondary)] w-28">
                              {k}
                            </span>
                            <span className="text-[var(--text-primary)]">
                              {String(v)}
                            </span>
                          </div>
                        ))}
                      <div className="pt-3 mt-2 border-t border-[var(--border)] flex justify-end">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleRemove(vc.id);
                          }}
                          disabled={removingId === vc.id}
                          className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-[var(--role-admin-text)] border border-[var(--role-admin-border)] rounded hover:bg-[var(--role-admin-bg)] disabled:opacity-50 transition-colors"
                        >
                          {removingId === vc.id ? (
                            <Loader2 size={12} className="animate-spin" />
                          ) : (
                            <Trash2 size={12} />
                          )}
                          Remove
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}