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 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 | 5x 9x 9x 9x 7x 2x 23x 23x 19x 4x 14x 14x 14x 14x 1x 13x 13x 3x 10x 10x 10x 5x 5x 10x 10x 14x 14x 4x 14x 14x 6x 14x 14x 5x 35x 3x 3x 3x 3x 11x 11x 9x 1x 11x 2x 24x 24x 24x 24x 24x 20x 20x 17x 17x 20x 24x 4x 4x 4x 16x 11x 11x 18x 9x 26x 26x 26x 26x 26x 26x 2x 24x 26x 26x 26x 24x 1x 1x 23x 3x 3x 20x 20x 26x 26x 1x 19x 17x 19x 8x 8x 8x 8x 8x 11x 26x 26x 8x 26x 26x 8x 3x 2x 2x 1x 3x 3x 3x 3x 3x 1x 2x 2x 2x | import { NextRequest, NextResponse } from "next/server";
import { DSP_PROTOCOL } from "@/lib/dsp-protocol";
import { edcClient, EDC_CONTEXT, newestFirstQuery } from "@/lib/edc";
import { requireAuth, isAuthError, type AuthSession } from "@/lib/auth-guard";
import { recordDemo, listDemo, DemoRecord } from "@/lib/demo-records";
import {
auditCallbackAddresses,
auditUnavailableResponse,
recordDspEvent,
recordDspEventAfter,
} from "@/lib/dsp-audit";
import { userToParticipantId } from "@/lib/odrl-engine";
import { loadTestId } from "@/lib/proxy";
import { pageFrom } from "@/lib/list-page";
import { identityOfContext } from "@/lib/edc/context-lookup";
import { tagRows } from "@/lib/row-provenance";
import {
PERMIT_ARTICLE,
checkPermit,
didFromCounterParty,
recordPermittedTransfer,
type PermitCheck,
} from "@/lib/permit-gate";
import { promises as fs } from "fs";
import path from "path";
export const dynamic = "force-dynamic";
/** Load demo transfers from the bundled mock JSON file. */
async function loadMockTransfers(): Promise<unknown[]> {
try {
const mockPath = path.join(
process.cwd(),
"public",
"mock",
"transfers.json",
);
const raw = await fs.readFile(mockPath, "utf-8");
return JSON.parse(raw) as unknown[];
} catch {
return [];
}
}
/**
* Load the bundled demo negotiations, whose agreements the transfer page offers.
*/
async function loadMockNegotiations(): Promise<unknown[]> {
try {
const raw = await fs.readFile(
path.join(process.cwd(), "public", "mock", "negotiations.json"),
"utf-8",
);
return JSON.parse(raw) as unknown[];
} catch {
return [];
}
}
/**
* GET /api/transfers?participantId=<id>[&limit=<n>&offset=<n>]: one page of
* the participant's transfers, newest first; `limit` 50 unless asked, at
* most 200 (lib/list-page.ts). The control plane's rows are merged with the
* demo and mock rows, which only the first page (offset 0) carries.
* POST /api/transfers: initiate a data transfer.
*/
export async function GET(req: NextRequest) {
const auth = await requireAuth();
Iif (isAuthError(auth)) return auth;
const participantId = req.nextUrl.searchParams.get("participantId");
if (!participantId) {
return NextResponse.json(
{ error: "participantId query parameter is required" },
{ status: 400 },
);
}
const page = pageFrom(req.nextUrl.searchParams);
if ("error" in page) {
return NextResponse.json({ error: page.error }, { status: 400 });
}
let realTransfers: unknown[] = [];
try {
realTransfers = await edcClient.management<unknown[]>(
`/v5/participants/${participantId}/transferprocesses/request`,
"POST",
newestFirstQuery(page.limit, page.offset),
);
Iif (!Array.isArray(realTransfers)) {
realTransfers = [];
}
} catch (err) {
console.warn(
"Controlplane transfer list unavailable, using demo data:",
err,
);
}
// Transfers this process recorded because the connector could not take them
// (see lib/demo-records.ts). They come first: the page refetches this list
// right after starting a transfer, and a row that vanishes on the refetch
// looks like a failure.
// Only the first page carries them, so a later page does not repeat them.
const firstPage = page.offset === 0;
const demoTransfers = firstPage ? listDemo("transfer", participantId) : [];
// Merge with demo transfers so the FHIR viewer is always demonstrable
const mockTransfers = firstPage ? await loadMockTransfers() : [];
const realIds = new Set(
realTransfers.map((t) => (t as Record<string, unknown>)["@id"]),
);
const taken = new Set([...realIds, ...demoTransfers.map((d) => d["@id"])]);
const deduped = mockTransfers.filter(
(m) => !taken.has((m as Record<string, unknown>)["@id"]),
);
// See #358 and lib/row-provenance.ts: the list merges three sources, the
// detail route asks only the control plane, so every row says which it is.
const merged = [
...tagRows(demoTransfers, "demo"),
...tagRows(realTransfers, "controlplane"),
...tagRows(deduped, "mock"),
];
return NextResponse.json(merged);
}
/** Mock agreement IDs follow pattern: agreement-fhir-<type>-<NNN> */
const MOCK_AGREEMENT_RE = /^agreement-fhir-[\w-]+-\d{3}$/;
/**
* True for a contract id the demonstrator minted itself, which therefore cannot
* exist in any connector: the synthetic agreements of the bundled fixtures, and
* the `demo-agreement:` ids that `POST /api/negotiations` records when the offer
* came from the demo catalogue rather than from a live DSP request (issue #25).
*/
function isInventedContractId(contractId: string): boolean {
return (
contractId.startsWith("demo-agreement:") ||
MOCK_AGREEMENT_RE.test(contractId)
);
}
/**
* True for an agreement that is only known from `public/mock/negotiations.json`.
*
* Two of those agreements are plain UUIDs left over from a seeded run, so their
* shape tells us nothing, and they are the first two rows the transfer page
* shows. "Start Transfer" on either of them sent a contract the connector has
* never heard of and printed the raw 502, which is the same dead end one step
* further down the walkthrough. Checked only after the connector has refused
* the transfer, so a genuinely live agreement is never diverted.
*/
async function isFixtureAgreement(contractId: string): Promise<boolean> {
const negotiations = await loadMockNegotiations();
return negotiations.some((n) => {
const r = n as Record<string, unknown>;
return (
r.contractAgreementId === contractId ||
r["edc:contractAgreementId"] === contractId
);
});
}
/**
* The graph DID of a participant context, from the identity the connector
* holds for it ("did:web:identityhub%3A7083:pharmaco" is PharmaCo's). Null
* when the connector does not answer, has no such context, or names a
* participant the graph does not know.
*/
async function participantContextDid(
participantId: string,
): Promise<string | null> {
try {
// The kept list (lib/edc/context-lookup.ts): a context's identity does
// not change between transfers, and this ran on every live one.
const identity = await identityOfContext(participantId);
if (!identity) return null;
// The host differs per deployment; the slug at the end names the
// participant on all of them.
const slug = decodeURIComponent(identity).split(":").pop() ?? "";
return didFromCounterParty(slug) ?? didFromCounterParty(identity);
} catch {
return null;
}
}
/**
* The consumer a transfer serves, whose data permit the gate checks. A data
* user transfers for itself. A data holder transfers for the counterparty of
* the agreement, which the demo records and the fixtures name. On a connector
* agreement the participant context that starts the transfer is the consumer,
* whoever is signed in: an operator acting as PharmaCo transfers under
* PharmaCo's permit, not under the one its login maps to. A caller may also
* name the consumer outright. Null when none of that resolves, and the gate
* then refuses, because a permit cannot be verified for nobody.
*/
async function consumerForTransfer(
session: AuthSession | undefined,
body: Record<string, unknown>,
participantId: string,
contractId: string,
): Promise<string | null> {
Iif (typeof body.consumerDid === "string" && body.consumerDid.trim()) {
return body.consumerDid.trim();
}
const roles = session?.roles ?? [];
const user = session?.user;
const callerDid = user
? userToParticipantId(user.email ?? user.name ?? user.id, roles)
: null;
if (roles.includes("DATA_USER") && callerDid) return callerDid;
const recorded = listDemo("negotiation", participantId).find(
(n) => n.contractAgreementId === contractId,
);
const fixture = (await loadMockNegotiations()).find((n) => {
const r = n as Record<string, unknown>;
return (
r.contractAgreementId === contractId ||
r["edc:contractAgreementId"] === contractId
);
}) as Record<string, unknown> | undefined;
const agreement = recorded ?? fixture;
if (agreement) {
// A negotiation the caller ran as consumer, or one this demonstrator
// recorded for the caller (always the consumer side), names the caller.
Iif (
(agreement.type === "CONSUMER" || agreement.demo === true) &&
callerDid
) {
return callerDid;
}
const did = didFromCounterParty(
agreement.counterPartyId as string | undefined,
);
if (did) return did;
} else if (!isInventedContractId(contractId)) {
// A minted contract never reached a connector, so it is not asked.
const did = await participantContextDid(participantId);
if (did) return did;
}
// A test session's did:web:ci.test:<persona> is kept: the transfer then
// says it was a test, where an unknown login names nobody.
return callerDid && !callerDid.startsWith("did:web:unknown:")
? callerDid
: null;
}
/** The transfer process recorded for a contract no connector can act on. */
function buildDemoTransfer(
contractId: string,
assetId: string,
transferType: string,
counterPartyAddress: string,
demoReason: string,
upstreamError?: string,
): DemoRecord {
return {
"@type": "TransferProcess",
// One id per contract, so starting the same transfer twice replaces the row
// instead of stacking duplicates. The contract's own demo- prefix is dropped
// rather than nested, which would read as demo-transfer:demo-agreement:x.
"@id": `demo-transfer:${contractId.replace(/^demo-agreement:/, "")}`,
state: "STARTED",
stateTimestamp: Date.now(),
type: "CONSUMER",
contractId,
assetId,
transferType,
counterPartyAddress,
demo: true,
demoReason,
...(upstreamError ? { upstreamError } : {}),
};
}
export async function POST(req: NextRequest) {
const auth = await requireAuth();
Iif (isAuthError(auth)) return auth;
try {
const body = await req.json();
const {
participantId,
contractId,
counterPartyAddress,
assetId,
transferType,
} = body;
if (!participantId || !contractId || !counterPartyAddress) {
return NextResponse.json(
{
error:
"participantId, contractId, and counterPartyAddress are required",
},
{ status: 400 },
);
}
const asset = assetId || "";
const resolvedType = transferType || "HttpData-PULL";
// The data permit gate (Regulation (EU) 2025/327, Art. 61(1)): a data user
// may access data for secondary use only under a permit the access body
// issued (Art. 68). Whichever path below would carry the transfer, none
// starts without one. This is what makes step 4b of the journey a gate
// rather than a status word. Issue #206, M3.
let permit: PermitCheck;
try {
const consumerDid = await consumerForTransfer(
auth.session,
body as Record<string, unknown>,
participantId,
contractId,
);
permit = await checkPermit({
consumerDid,
datasetId: typeof body.datasetId === "string" ? body.datasetId : null,
assetId: asset,
});
} catch (err) {
await recordDspEventAfter({
process: "transfer-process",
event: "refused",
outcome: "refused",
loadTest: loadTestId(req),
agreementId: contractId,
assetId: asset || undefined,
participantContext: participantId,
reason: "data permit register unreachable",
});
return NextResponse.json(
{
error:
"The data permit register is unreachable; a transfer is not allowed without it",
detail: err instanceof Error ? err.message : String(err),
article: PERMIT_ARTICLE,
},
{ status: 503 },
);
}
if (!permit.allowed) {
// A refused access is on the trail too: the access body has to be able
// to show what was asked for without a permit, not only what flowed.
await recordDspEventAfter({
process: "transfer-process",
event: "refused",
outcome: "refused",
loadTest: loadTestId(req),
agreementId: contractId,
assetId: asset || undefined,
consumerId: permit.consumerDid ?? undefined,
permitId: permit.permitId ?? undefined,
participantContext: participantId,
reason: permit.reason,
});
return NextResponse.json(
{
error: "No data permit covers this transfer",
reason: permit.reason,
article: permit.article,
consumerDid: permit.consumerDid,
permitId: permit.permitId,
},
{ status: 403 },
);
}
const permitStamp = {
permitId: permit.permitId,
permitDataset: permit.datasetId,
permitDatasetMatched: permit.datasetMatched,
permitValidUntil: permit.validUntil,
permitArticle: permit.article,
};
// On the audit trail before anything is sent, or not at all (ADR-045).
const audited = {
process: "transfer-process" as const,
loadTest: loadTestId(req),
agreementId: contractId,
assetId: asset || undefined,
datasetId: permit.datasetId ?? undefined,
permitId: permit.permitId ?? undefined,
consumerId: permit.consumerDid ?? undefined,
participantContext: participantId,
};
try {
await recordDspEvent({
...audited,
event: "requested",
outcome: "success",
});
} catch (err) {
return auditUnavailableResponse(err);
}
const audit = (transferId: string, demo: boolean) =>
void recordPermittedTransfer({
transferId,
contractId,
assetId: asset,
consumerDid: permit.consumerDid as string,
permitId: permit.permitId as string,
datasetId: permit.datasetId,
demo,
});
// Demo-mode: a contract this demonstrator minted itself cannot exist in any
// connector, so there is nothing to ask. Record the transfer and label it.
if (isInventedContractId(contractId)) {
const demo = {
...buildDemoTransfer(
contractId,
asset,
resolvedType,
counterPartyAddress,
"This contract was recorded by the demonstrator rather than agreed over DSP, " +
"so the transfer was recorded here too instead of being sent to the " +
"connector, which has never seen the contract. The FHIR payload below is " +
"the demonstrator's own. Tracked in issue #25.",
),
...permitStamp,
};
recordDemo("transfer", participantId, demo);
audit(demo["@id"], true);
await recordDspEventAfter({
...audited,
event: "started",
outcome: "success",
processId: demo["@id"],
demo: true,
});
return NextResponse.json(demo, { status: 201 });
}
const transferPayload = {
"@context": [EDC_CONTEXT],
"@type": "TransferRequest",
counterPartyAddress,
protocol: DSP_PROTOCOL,
contractId,
assetId: asset,
transferType: resolvedType,
dataDestination: {
"@type": "DataAddress",
type: "HttpProxy",
},
// Every state of this transfer reaches the audit trail (ADR-045, #418).
...(auditCallbackAddresses("transfer.process").length > 0
? { callbackAddresses: auditCallbackAddresses("transfer.process") }
: {}),
};
try {
const result = await edcClient.management<Record<string, unknown>>(
`/v5/participants/${participantId}/transferprocesses`,
"POST",
transferPayload,
);
const id =
result && typeof result["@id"] === "string"
? (result["@id"] as string)
: `transfer:${contractId}`;
audit(id, false);
await recordDspEventAfter({
...audited,
event: "initiated",
outcome: "success",
processId: id,
});
return NextResponse.json({ ...result, ...permitStamp }, { status: 201 });
} catch (err) {
// An agreement that only exists in the bundled fixtures looks real (two of
// them are UUIDs from an old seeded run), so it is tried against the
// connector first and only diverted once the connector has refused it. A
// genuinely live agreement that fails still returns the 502 below, because
// that is a real fault and hiding it would be worse than the original bug.
if (!(await isFixtureAgreement(contractId))) {
await recordDspEventAfter({
...audited,
event: "failed",
outcome: "failure",
reason: err instanceof Error ? err.message : String(err),
});
throw err;
}
const msg = err instanceof Error ? err.message : String(err);
console.warn("Demo agreement transferred without a connector:", msg);
const demo = {
...buildDemoTransfer(
contractId,
asset,
resolvedType,
counterPartyAddress,
"This agreement comes from the demonstrator's own negotiation history, so " +
"the connector has no contract to transfer under. The transfer was " +
"recorded here and the FHIR payload below is the demonstrator's own. " +
"Tracked in issue #25.",
msg,
),
...permitStamp,
};
recordDemo("transfer", participantId, demo);
audit(demo["@id"], true);
await recordDspEventAfter({
...audited,
event: "started",
outcome: "success",
processId: demo["@id"],
demo: true,
});
return NextResponse.json(demo, { status: 201 });
}
} catch (err) {
console.error("Failed to initiate transfer:", err);
const detail =
err instanceof Error ? err.message : "Failed to initiate data transfer";
return NextResponse.json({ error: detail }, { status: 502 });
}
}
|