forked from Asyboi/agentic-hack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
144 lines (125 loc) · 4.02 KB
/
Copy pathmiddleware.ts
File metadata and controls
144 lines (125 loc) · 4.02 KB
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
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { x402HTTPResourceServer } from "@x402/core/http";
import {
createX402Routes,
x402HasCdpCredentials,
x402Mode,
x402ResourceServerInstance,
} from "@/lib/x402-payment";
function getPublicOrigin(request: NextRequest): `${string}://${string}` {
const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0];
const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0];
const protocol = forwardedProto || request.nextUrl.protocol.replace(":", "");
const host = forwardedHost || request.headers.get("host") || request.nextUrl.host;
return `${protocol}://${host}`;
}
function toNextResponse(response: {
status: number;
headers: Record<string, string>;
body?: unknown;
isHtml?: boolean;
}) {
const headers = new Headers(response.headers);
if (response.body === undefined) {
return new NextResponse(null, { status: response.status, headers });
}
if (typeof response.body === "string") {
return new NextResponse(response.body, { status: response.status, headers });
}
if (!response.isHtml && !headers.has("content-type")) {
headers.set("content-type", "application/json");
}
return new NextResponse(JSON.stringify(response.body), {
status: response.status,
headers,
});
}
function createRequestContext(request: NextRequest) {
return {
adapter: {
getHeader: (name: string) => request.headers.get(name) ?? undefined,
getMethod: () => request.method,
getPath: () => request.nextUrl.pathname,
getUrl: () => request.url,
getAcceptHeader: () => request.headers.get("accept") ?? "",
getUserAgent: () => request.headers.get("user-agent") ?? "",
getQueryParams: () =>
Object.fromEntries(request.nextUrl.searchParams.entries()),
getQueryParam: (name: string) =>
request.nextUrl.searchParams.get(name) ?? undefined,
},
path: request.nextUrl.pathname,
method: request.method,
paymentHeader:
request.headers.get("x-payment") ??
request.headers.get("payment") ??
undefined,
};
}
export async function middleware(request: NextRequest) {
if (x402Mode !== "live") {
return NextResponse.next();
}
if (!x402HasCdpCredentials) {
return NextResponse.json(
{
error: "CDP credentials required",
message:
"Set CDP_API_KEY_ID and CDP_API_KEY_SECRET in .env.local to use X402_MODE=live with the CDP Facilitator.",
},
{ status: 500 }
);
}
const httpServer = new x402HTTPResourceServer(
x402ResourceServerInstance,
createX402Routes(getPublicOrigin(request))
);
try {
await httpServer.initialize();
} catch (error) {
return NextResponse.json(
{
error: "x402 initialization failed",
message: error instanceof Error ? error.message : String(error),
},
{ status: 500 }
);
}
const requestContext = createRequestContext(request);
const paymentResult = await httpServer.processHTTPRequest(requestContext);
if (paymentResult.type === "no-payment-required") {
return NextResponse.next();
}
if (paymentResult.type === "payment-error") {
return toNextResponse(paymentResult.response);
}
const response = NextResponse.next();
const settlement = await httpServer.processSettlement(
paymentResult.paymentPayload,
paymentResult.paymentRequirements,
paymentResult.declaredExtensions,
{ request: requestContext }
);
if (!settlement.success) {
return NextResponse.json(
{
error: "x402 settlement failed",
reason: settlement.errorReason,
message: settlement.errorMessage,
},
{
status: settlement.response.status,
headers: settlement.response.headers,
}
);
}
for (const [key, value] of Object.entries(settlement.headers)) {
response.headers.set(key, value);
}
return response;
}
export const config = {
matcher: ["/api/paid-demo", "/api/evaluate", "/api/research"],
runtime: "nodejs",
};