@hilbras/sdk 3.4.4 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/frameworks/astro/endpoints.js +58 -16
- package/dist/frameworks/astro/index.d.ts +1 -0
- package/dist/frameworks/nextjs/api/index.d.ts +15 -0
- package/dist/frameworks/nextjs/api/index.js +14 -0
- package/dist/frameworks/nextjs/api/stream.d.ts +44 -0
- package/dist/frameworks/nextjs/api/stream.js +150 -0
- package/dist/frameworks/nextjs/edge/index.d.ts +12 -0
- package/dist/frameworks/nextjs/edge/index.js +11 -0
- package/dist/frameworks/nextjs/edge/middleware.d.ts +85 -0
- package/dist/frameworks/nextjs/edge/middleware.js +113 -0
- package/dist/frameworks/nextjs/index.d.ts +1 -0
- package/dist/frameworks/nextjs/next-runtime.d.ts +63 -0
- package/dist/frameworks/nextjs/next-runtime.js +41 -0
- package/dist/frameworks/nextjs/route-handlers.js +51 -27
- package/dist/frameworks/nextjs/server.d.ts +24 -1
- package/dist/frameworks/nextjs/server.js +24 -1
- package/dist/frameworks/remix/actions.js +58 -16
- package/dist/frameworks/remix/index.d.ts +1 -0
- package/dist/frameworks/shared/handler-core.d.ts +143 -2
- package/dist/frameworks/shared/handler-core.js +134 -5
- package/package.json +10 -2
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="https://img.shields.io/badge/version-3.
|
|
2
|
+
<img src="https://img.shields.io/badge/version-3.5.0-blue" alt="version">
|
|
3
3
|
<img src="https://img.shields.io/badge/license-MIT-green" alt="license">
|
|
4
4
|
<img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen" alt="node">
|
|
5
5
|
<img src="https://img.shields.io/badge/types-strict-blueviolet" alt="types">
|
|
6
|
-
<img src="https://img.shields.io/badge/tests-
|
|
6
|
+
<img src="https://img.shields.io/badge/tests-1932%20passing-brightgreen" alt="tests">
|
|
7
7
|
<img src="https://img.shields.io/badge/runtime%20deps-zero-brightgreen" alt="zero deps">
|
|
8
8
|
</p>
|
|
9
9
|
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Uses the HilbrasClient to generate streaming responses with full protocol support.
|
|
6
6
|
*/
|
|
7
7
|
import { createSSEResponse } from "../../utils/sse-writer.js";
|
|
8
|
-
import { createFrameworkClientPool, errorResponse, readJsonBody,
|
|
8
|
+
import { createFrameworkClientPool, errorResponse, isRequestPhaseError, readJsonBody, resolveChatFields, resolveCompletionFields, resolveLimits, } from "../shared/handler-core.js";
|
|
9
9
|
/**
|
|
10
10
|
* Create a streaming chat endpoint for Astro.
|
|
11
11
|
*
|
|
@@ -26,20 +26,35 @@ export function createChatEndpoint(options) {
|
|
|
26
26
|
model: options.model,
|
|
27
27
|
apiKey: options.apiKey,
|
|
28
28
|
});
|
|
29
|
+
const limits = resolveLimits(options.limits);
|
|
30
|
+
// This adapter never read `model`/`tools`/`maxSteps` from the body in v3.4, so
|
|
31
|
+
// its default is `false`. Defaulting to `true` would have widened the
|
|
32
|
+
// caller's influence over a route that did not previously have any.
|
|
33
|
+
const trustClientFields = options.trustClientFields ?? false;
|
|
29
34
|
async function POST({ request }) {
|
|
30
35
|
try {
|
|
31
|
-
const body = await readJsonBody(request);
|
|
32
|
-
const
|
|
33
|
-
|
|
36
|
+
const body = await readJsonBody(request, limits);
|
|
37
|
+
const fields = resolveChatFields(body, {
|
|
38
|
+
model: options.model,
|
|
39
|
+
tools: options.tools,
|
|
40
|
+
maxSteps: options.maxSteps,
|
|
41
|
+
trustClientFields,
|
|
42
|
+
limits,
|
|
43
|
+
});
|
|
44
|
+
const client = pool.get(fields.model);
|
|
34
45
|
const providerName = pool.providerName;
|
|
46
|
+
const effective = { ...fields, provider: providerName };
|
|
47
|
+
await options.onRequest?.({ request, body, effective });
|
|
35
48
|
const allMessages = options.systemPrompt
|
|
36
|
-
? [{ role: "system", content: options.systemPrompt }, ...messages]
|
|
37
|
-
: messages;
|
|
38
|
-
if (
|
|
49
|
+
? [{ role: "system", content: options.systemPrompt }, ...fields.messages]
|
|
50
|
+
: fields.messages;
|
|
51
|
+
if (!effective.stream) {
|
|
39
52
|
const result = await client.complete({
|
|
40
53
|
provider: providerName,
|
|
41
|
-
model:
|
|
54
|
+
model: fields.model,
|
|
42
55
|
messages: allMessages,
|
|
56
|
+
temperature: fields.temperature,
|
|
57
|
+
maxTokens: fields.maxTokens,
|
|
43
58
|
signal: request.signal,
|
|
44
59
|
});
|
|
45
60
|
return new Response(JSON.stringify({
|
|
@@ -51,15 +66,23 @@ export function createChatEndpoint(options) {
|
|
|
51
66
|
}
|
|
52
67
|
const chunks = client.streamText({
|
|
53
68
|
provider: providerName,
|
|
54
|
-
model:
|
|
69
|
+
model: fields.model,
|
|
55
70
|
messages: allMessages,
|
|
56
|
-
|
|
57
|
-
|
|
71
|
+
temperature: fields.temperature,
|
|
72
|
+
maxTokens: fields.maxTokens,
|
|
73
|
+
tools: fields.tools,
|
|
74
|
+
maxSteps: fields.maxSteps,
|
|
58
75
|
signal: request.signal,
|
|
59
76
|
});
|
|
60
77
|
return createSSEResponse(chunks);
|
|
61
78
|
}
|
|
62
79
|
catch (error) {
|
|
80
|
+
if (options.onError) {
|
|
81
|
+
await options.onError(error, {
|
|
82
|
+
request,
|
|
83
|
+
phase: isRequestPhaseError(error) ? "request" : "provider",
|
|
84
|
+
});
|
|
85
|
+
}
|
|
63
86
|
return errorResponse(error);
|
|
64
87
|
}
|
|
65
88
|
}
|
|
@@ -77,15 +100,28 @@ export function createCompletionEndpoint(options) {
|
|
|
77
100
|
model: options.model,
|
|
78
101
|
apiKey: options.apiKey,
|
|
79
102
|
});
|
|
103
|
+
const limits = resolveLimits(options.limits);
|
|
104
|
+
// This adapter never read `model`/`tools`/`maxSteps` from the body in v3.4, so
|
|
105
|
+
// its default is `false`. Defaulting to `true` would have widened the
|
|
106
|
+
// caller's influence over a route that did not previously have any.
|
|
107
|
+
const trustClientFields = options.trustClientFields ?? false;
|
|
80
108
|
async function POST({ request }) {
|
|
81
109
|
try {
|
|
82
|
-
const body = await readJsonBody(request);
|
|
83
|
-
const
|
|
84
|
-
|
|
110
|
+
const body = await readJsonBody(request, limits);
|
|
111
|
+
const fields = resolveCompletionFields(body, {
|
|
112
|
+
model: options.model,
|
|
113
|
+
trustClientFields,
|
|
114
|
+
limits,
|
|
115
|
+
});
|
|
116
|
+
const client = pool.get(fields.model);
|
|
117
|
+
const effective = { ...fields, provider: pool.providerName };
|
|
118
|
+
await options.onRequest?.({ request, body, effective });
|
|
85
119
|
const result = await client.complete({
|
|
86
120
|
provider: pool.providerName,
|
|
87
|
-
model:
|
|
88
|
-
messages: [{ role: "user", content: prompt }],
|
|
121
|
+
model: fields.model,
|
|
122
|
+
messages: [{ role: "user", content: fields.prompt }],
|
|
123
|
+
temperature: fields.temperature,
|
|
124
|
+
maxTokens: fields.maxTokens,
|
|
89
125
|
signal: request.signal,
|
|
90
126
|
});
|
|
91
127
|
return new Response(JSON.stringify({
|
|
@@ -96,6 +132,12 @@ export function createCompletionEndpoint(options) {
|
|
|
96
132
|
});
|
|
97
133
|
}
|
|
98
134
|
catch (error) {
|
|
135
|
+
if (options.onError) {
|
|
136
|
+
await options.onError(error, {
|
|
137
|
+
request,
|
|
138
|
+
phase: isRequestPhaseError(error) ? "request" : "provider",
|
|
139
|
+
});
|
|
140
|
+
}
|
|
99
141
|
return errorResponse(error);
|
|
100
142
|
}
|
|
101
143
|
}
|
|
@@ -4,4 +4,5 @@
|
|
|
4
4
|
* API endpoints and client-side hooks for Astro.
|
|
5
5
|
*/
|
|
6
6
|
export { createChatEndpoint, createCompletionEndpoint, type EndpointOptions, type ChatMessage } from "./endpoints.js";
|
|
7
|
+
export type { FrameworkErrorContext, FrameworkHandlerLimits, FrameworkRequestContext, } from "../shared/handler-core.js";
|
|
7
8
|
export { createChatState, type UseChatOptions, type UseChatReturn, type Message } from "./hooks.js";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Next.js API route helpers
|
|
3
|
+
*
|
|
4
|
+
* Subpath: `@hilbras/sdk/nextjs/api`
|
|
5
|
+
*
|
|
6
|
+
* These helpers import `next/server`, so they live under their own subpath
|
|
7
|
+
* rather than in `@hilbras/sdk/nextjs`. The `./nextjs` entry must keep working
|
|
8
|
+
* in a project with no `next` installed, and re-exporting these from there
|
|
9
|
+
* would make `next/server` a hard resolution requirement for every consumer.
|
|
10
|
+
*
|
|
11
|
+
* `createChatHandler` and friends — which take a plain `Request` and return a
|
|
12
|
+
* plain `Response` and need no Next types at all — remain in `@hilbras/sdk/nextjs`.
|
|
13
|
+
*/
|
|
14
|
+
export { createStreamHandler, createStreamCompletionHandler } from "./stream.js";
|
|
15
|
+
export type { ChatMessage, StreamChatOptions, StreamCompletionOptions } from "./stream.js";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Next.js API route helpers
|
|
3
|
+
*
|
|
4
|
+
* Subpath: `@hilbras/sdk/nextjs/api`
|
|
5
|
+
*
|
|
6
|
+
* These helpers import `next/server`, so they live under their own subpath
|
|
7
|
+
* rather than in `@hilbras/sdk/nextjs`. The `./nextjs` entry must keep working
|
|
8
|
+
* in a project with no `next` installed, and re-exporting these from there
|
|
9
|
+
* would make `next/server` a hard resolution requirement for every consumer.
|
|
10
|
+
*
|
|
11
|
+
* `createChatHandler` and friends — which take a plain `Request` and return a
|
|
12
|
+
* plain `Response` and need no Next types at all — remain in `@hilbras/sdk/nextjs`.
|
|
13
|
+
*/
|
|
14
|
+
export { createStreamHandler, createStreamCompletionHandler } from "./stream.js";
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { HilbrasClient, type HilbrasClientConfig } from "../../../client/client.js";
|
|
2
|
+
import type { Message } from "../../../types/messages.js";
|
|
3
|
+
import { type NextRequestLike } from "../next-runtime.js";
|
|
4
|
+
export type ChatMessage = Message;
|
|
5
|
+
export interface StreamChatOptions {
|
|
6
|
+
/** HilbrasClient config (creates a new client if not provided) */
|
|
7
|
+
config?: HilbrasClientConfig;
|
|
8
|
+
/** Pre-existing client instance */
|
|
9
|
+
client?: HilbrasClient;
|
|
10
|
+
/** Catalog provider id used when this helper creates the client */
|
|
11
|
+
provider: string;
|
|
12
|
+
/** Default model */
|
|
13
|
+
model: string;
|
|
14
|
+
/** Credential for a newly created catalog-backed client */
|
|
15
|
+
apiKey?: string;
|
|
16
|
+
/** System prompt */
|
|
17
|
+
systemPrompt?: string;
|
|
18
|
+
/** Custom error handler */
|
|
19
|
+
onError?: (error: Error) => Response | Promise<Response>;
|
|
20
|
+
/** Called before streaming starts */
|
|
21
|
+
onRequest?: (messages: ChatMessage[]) => void | Promise<void>;
|
|
22
|
+
/** Called after streaming completes */
|
|
23
|
+
onComplete?: (messages: ChatMessage[], usage: {
|
|
24
|
+
inputTokens: number;
|
|
25
|
+
outputTokens: number;
|
|
26
|
+
}) => void | Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
/** Create a streaming chat API route for Next.js App Router. */
|
|
29
|
+
export declare function createStreamHandler(options: StreamChatOptions): {
|
|
30
|
+
POST: (request: NextRequestLike) => Promise<import("../next-runtime.js").HilbrasNextResponse | Response>;
|
|
31
|
+
};
|
|
32
|
+
export interface StreamCompletionOptions {
|
|
33
|
+
config?: HilbrasClientConfig;
|
|
34
|
+
client?: HilbrasClient;
|
|
35
|
+
provider: string;
|
|
36
|
+
model: string;
|
|
37
|
+
apiKey?: string;
|
|
38
|
+
systemPrompt?: string;
|
|
39
|
+
onError?: (error: Error) => Response | Promise<Response>;
|
|
40
|
+
}
|
|
41
|
+
/** Create a streaming text-completion API route. */
|
|
42
|
+
export declare function createStreamCompletionHandler(options: StreamCompletionOptions): {
|
|
43
|
+
POST: (request: NextRequestLike) => Promise<import("../next-runtime.js").HilbrasNextResponse | Response>;
|
|
44
|
+
};
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { HilbrasClient, } from "../../../client/client.js";
|
|
2
|
+
import { createNextResponseShim, } from "../next-runtime.js";
|
|
3
|
+
const NextResponse = createNextResponseShim();
|
|
4
|
+
const ROLES = new Set(["system", "user", "assistant", "tool"]);
|
|
5
|
+
function parseMessages(value) {
|
|
6
|
+
if (!Array.isArray(value))
|
|
7
|
+
throw new Error("Request body must include a messages array");
|
|
8
|
+
return value.map((message) => {
|
|
9
|
+
if (typeof message !== "object" || message === null) {
|
|
10
|
+
throw new Error("Each message must be an object");
|
|
11
|
+
}
|
|
12
|
+
const candidate = message;
|
|
13
|
+
if (typeof candidate.role !== "string" || !ROLES.has(candidate.role)) {
|
|
14
|
+
throw new Error("Message role is invalid");
|
|
15
|
+
}
|
|
16
|
+
if (typeof candidate.content !== "string" && candidate.content !== null && !Array.isArray(candidate.content)) {
|
|
17
|
+
throw new Error("Message content is invalid");
|
|
18
|
+
}
|
|
19
|
+
return candidate;
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
function createRouteClient(options) {
|
|
23
|
+
if (options.client)
|
|
24
|
+
return { client: options.client, provider: options.provider };
|
|
25
|
+
const client = new HilbrasClient(options.config);
|
|
26
|
+
const provider = client.addProviderFromCatalog(options.provider, options.model, options.apiKey ?? process.env.HILBRAS_API_KEY ?? "");
|
|
27
|
+
return { client, provider };
|
|
28
|
+
}
|
|
29
|
+
/** Create a streaming chat API route for Next.js App Router. */
|
|
30
|
+
export function createStreamHandler(options) {
|
|
31
|
+
const { config, client: existingClient, provider, model, systemPrompt, apiKey, onError, onRequest, onComplete } = options;
|
|
32
|
+
const route = createRouteClient({ config, client: existingClient, apiKey, provider, model });
|
|
33
|
+
async function POST(request) {
|
|
34
|
+
try {
|
|
35
|
+
const body = await request.json();
|
|
36
|
+
const record = typeof body === "object" && body !== null ? body : {};
|
|
37
|
+
const messages = parseMessages(record.messages);
|
|
38
|
+
await onRequest?.(messages);
|
|
39
|
+
const apiMessages = [];
|
|
40
|
+
if (systemPrompt)
|
|
41
|
+
apiMessages.push({ role: "system", content: systemPrompt });
|
|
42
|
+
apiMessages.push(...messages);
|
|
43
|
+
const stream = new ReadableStream({
|
|
44
|
+
async start(controller) {
|
|
45
|
+
const encoder = new TextEncoder();
|
|
46
|
+
let inputTokens = 0;
|
|
47
|
+
let outputTokens = 0;
|
|
48
|
+
try {
|
|
49
|
+
for await (const chunk of route.client.stream({
|
|
50
|
+
messages: apiMessages,
|
|
51
|
+
model,
|
|
52
|
+
provider: route.provider,
|
|
53
|
+
signal: request.signal,
|
|
54
|
+
})) {
|
|
55
|
+
if (chunk.type === "text") {
|
|
56
|
+
controller.enqueue(encoder.encode(`0:${JSON.stringify(chunk.text)}\n`));
|
|
57
|
+
}
|
|
58
|
+
else if (chunk.type === "usage") {
|
|
59
|
+
inputTokens = chunk.inputTokens;
|
|
60
|
+
outputTokens = chunk.outputTokens;
|
|
61
|
+
controller.enqueue(encoder.encode(`1:${JSON.stringify({ inputTokens, outputTokens })}\n`));
|
|
62
|
+
}
|
|
63
|
+
else if (chunk.type === "finish") {
|
|
64
|
+
controller.enqueue(encoder.encode(`2:${JSON.stringify(chunk.reason)}\n`));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
await onComplete?.(messages, { inputTokens, outputTokens });
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
71
|
+
await onError?.(error);
|
|
72
|
+
controller.enqueue(encoder.encode(`3:${JSON.stringify("stream_failed")}\n`));
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
controller.close();
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
return new Response(stream, {
|
|
80
|
+
headers: {
|
|
81
|
+
"Content-Type": "application/x-ndjson; charset=utf-8",
|
|
82
|
+
"Cache-Control": "no-cache, no-transform",
|
|
83
|
+
"Connection": "keep-alive",
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
89
|
+
if (onError)
|
|
90
|
+
return onError(error);
|
|
91
|
+
return NextResponse.json({ error: "Request failed" }, { status: 400 });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return { POST };
|
|
95
|
+
}
|
|
96
|
+
/** Create a streaming text-completion API route. */
|
|
97
|
+
export function createStreamCompletionHandler(options) {
|
|
98
|
+
const { config, client: existingClient, provider, model, systemPrompt, apiKey, onError } = options;
|
|
99
|
+
const route = createRouteClient({ config, client: existingClient, apiKey, provider, model });
|
|
100
|
+
async function POST(request) {
|
|
101
|
+
try {
|
|
102
|
+
const body = await request.json();
|
|
103
|
+
const record = typeof body === "object" && body !== null ? body : {};
|
|
104
|
+
if (typeof record.prompt !== "string" || !record.prompt.trim()) {
|
|
105
|
+
throw new Error("Request body must include a non-empty prompt");
|
|
106
|
+
}
|
|
107
|
+
const apiMessages = [];
|
|
108
|
+
if (systemPrompt)
|
|
109
|
+
apiMessages.push({ role: "system", content: systemPrompt });
|
|
110
|
+
apiMessages.push({ role: "user", content: record.prompt });
|
|
111
|
+
const stream = new ReadableStream({
|
|
112
|
+
async start(controller) {
|
|
113
|
+
const encoder = new TextEncoder();
|
|
114
|
+
try {
|
|
115
|
+
for await (const chunk of route.client.stream({
|
|
116
|
+
messages: apiMessages,
|
|
117
|
+
model,
|
|
118
|
+
provider: route.provider,
|
|
119
|
+
signal: request.signal,
|
|
120
|
+
})) {
|
|
121
|
+
if (chunk.type === "text")
|
|
122
|
+
controller.enqueue(encoder.encode(chunk.text));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
127
|
+
await onError?.(error);
|
|
128
|
+
controller.enqueue(encoder.encode("stream_failed"));
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
controller.close();
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
return new Response(stream, {
|
|
136
|
+
headers: {
|
|
137
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
138
|
+
"Cache-Control": "no-cache, no-transform",
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
catch (err) {
|
|
143
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
144
|
+
if (onError)
|
|
145
|
+
return onError(error);
|
|
146
|
+
return NextResponse.json({ error: "Request failed" }, { status: 400 });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return { POST };
|
|
150
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Next.js edge middleware
|
|
3
|
+
*
|
|
4
|
+
* Subpath: `@hilbras/sdk/nextjs/edge`
|
|
5
|
+
*
|
|
6
|
+
* `hilbrasMiddleware` implements the rate-limit bucket keying. It is typed
|
|
7
|
+
* structurally against the Next request surface rather than importing
|
|
8
|
+
* `next/server`, and it has its own subpath so that `@hilbras/sdk/nextjs` stays
|
|
9
|
+
* importable in a project with no Next dependency.
|
|
10
|
+
*/
|
|
11
|
+
export { hilbrasMiddleware, forwardedClientIp } from "./middleware.js";
|
|
12
|
+
export type { HilbrasMiddlewareOptions, RateLimitStore } from "./middleware.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Next.js edge middleware
|
|
3
|
+
*
|
|
4
|
+
* Subpath: `@hilbras/sdk/nextjs/edge`
|
|
5
|
+
*
|
|
6
|
+
* `hilbrasMiddleware` implements the rate-limit bucket keying. It is typed
|
|
7
|
+
* structurally against the Next request surface rather than importing
|
|
8
|
+
* `next/server`, and it has its own subpath so that `@hilbras/sdk/nextjs` stays
|
|
9
|
+
* importable in a project with no Next dependency.
|
|
10
|
+
*/
|
|
11
|
+
export { hilbrasMiddleware, forwardedClientIp } from "./middleware.js";
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { type NextRequestLike } from "../next-runtime.js";
|
|
2
|
+
export interface HilbrasMiddlewareOptions {
|
|
3
|
+
/** Rate limit: max requests per window (default: 60) */
|
|
4
|
+
maxRequests?: number;
|
|
5
|
+
/** Rate limit: window duration in seconds (default: 60) */
|
|
6
|
+
windowSeconds?: number;
|
|
7
|
+
/** Paths to exclude from middleware (default: ["/_next", "/favicon.ico"]) */
|
|
8
|
+
excludePaths?: string[];
|
|
9
|
+
/** Custom error response */
|
|
10
|
+
onError?: (error: string) => Response;
|
|
11
|
+
/**
|
|
12
|
+
* How many trusted reverse proxies sit in front of the app.
|
|
13
|
+
*
|
|
14
|
+
* `x-forwarded-for` is a comma-separated list that each proxy appends to, so
|
|
15
|
+
* the real client address sits `trustProxy` entries from the **right**. Taking
|
|
16
|
+
* the leftmost entry — which is what this middleware did before 2.3.0 — reads
|
|
17
|
+
* the value the *client* supplied, because the common proxies (nginx
|
|
18
|
+
* `proxy_add_x_forwarded_for`, Vercel, Cloudflare) prepend the real address to
|
|
19
|
+
* whatever the client sent. An attacker who rotated the header therefore got a
|
|
20
|
+
* fresh rate-limit bucket per request.
|
|
21
|
+
*
|
|
22
|
+
* Defaults to `0`: trust the rightmost entry, i.e. the address added by the
|
|
23
|
+
* proxy directly in front of you. Correct for a single proxy, and safe for
|
|
24
|
+
* none — see `fallbackKey`.
|
|
25
|
+
*
|
|
26
|
+
* Set this to the number of proxies in your chain. With no proxy at all,
|
|
27
|
+
* leave it at `0` and supply `fallbackKey`.
|
|
28
|
+
*/
|
|
29
|
+
trustProxy?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Key derivation for the rate-limit bucket, used when no trustworthy forwarded
|
|
32
|
+
* address is available.
|
|
33
|
+
*/
|
|
34
|
+
fallbackKey?: (request: NextRequestLike) => string;
|
|
35
|
+
/**
|
|
36
|
+
* Counter backend. The default is in-process `Map` state, which is correct
|
|
37
|
+
* for a single instance or a dev server. Behind more than one instance each
|
|
38
|
+
* keeps its own counter, so the effective limit becomes
|
|
39
|
+
* `maxRequests × instances`. Pass a shared store (Redis, KV, or anything with
|
|
40
|
+
* a `hit` method) to make the limit global; that store must expire its own
|
|
41
|
+
* keys.
|
|
42
|
+
*/
|
|
43
|
+
store?: RateLimitStore;
|
|
44
|
+
}
|
|
45
|
+
/** A counter backend. Entries must expire themselves. */
|
|
46
|
+
export interface RateLimitStore {
|
|
47
|
+
/** Increment and return the counter for `key` within a `windowMs` window. */
|
|
48
|
+
hit(key: string, windowMs: number): Promise<{
|
|
49
|
+
count: number;
|
|
50
|
+
resetAt: number;
|
|
51
|
+
}>;
|
|
52
|
+
/** Drop expired entries. Optional — a shared store expires its own keys. */
|
|
53
|
+
cleanup?(): void | Promise<void>;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Extract the client address from a `x-forwarded-for` list.
|
|
57
|
+
*
|
|
58
|
+
* Each proxy *appends* the address it saw, so the list reads
|
|
59
|
+
* `client-supplied, …, nearest-hop`. With `trustProxy` trusted proxies the real
|
|
60
|
+
* client sits `trustProxy` entries from the right, which is index
|
|
61
|
+
* `entries.length - trustProxy`:
|
|
62
|
+
*
|
|
63
|
+
* - `trustProxy: 0` — index `length`, i.e. out of range. Nothing is trusted, so
|
|
64
|
+
* there is no entry we can attribute to the client rather than to a proxy.
|
|
65
|
+
* - `trustProxy: 1` — `"9.9.9.1, 1.1.1.1"` gives index 1, the real client, and
|
|
66
|
+
* `9.9.9.1` (the attacker's) is correctly ignored.
|
|
67
|
+
* - `trustProxy: 2` — `"9.9.9.1, 1.1.1.1, 10.0.0.1"` gives index 1 again.
|
|
68
|
+
*
|
|
69
|
+
* Returns `undefined` when the list is absent or shorter than the trust depth,
|
|
70
|
+
* because in that case every entry present was chosen by the client.
|
|
71
|
+
*/
|
|
72
|
+
export declare function forwardedClientIp(headerValue: string | null | undefined, trustProxy: number): string | undefined;
|
|
73
|
+
/**
|
|
74
|
+
* Next.js middleware for rate limiting AI API routes.
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```ts
|
|
78
|
+
* // middleware.ts
|
|
79
|
+
* import { hilbrasMiddleware } from "@hilbras/sdk/nextjs/edge";
|
|
80
|
+
*
|
|
81
|
+
* export const config = { matcher: ["/api/:path*"] };
|
|
82
|
+
* export default hilbrasMiddleware({ maxRequests: 30, trustProxy: 1 });
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
export declare function hilbrasMiddleware(options?: HilbrasMiddlewareOptions): (request: NextRequestLike) => Promise<import("../next-runtime.js").HilbrasNextResponse | Response>;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createNextResponseShim, } from "../next-runtime.js";
|
|
2
|
+
const NextResponse = createNextResponseShim();
|
|
3
|
+
/** In-process store. Not shared across instances — see `store`. */
|
|
4
|
+
function createMemoryStore() {
|
|
5
|
+
const hits = new Map();
|
|
6
|
+
return {
|
|
7
|
+
async hit(key, windowMs) {
|
|
8
|
+
const now = Date.now();
|
|
9
|
+
const entry = hits.get(key);
|
|
10
|
+
if (!entry || now > entry.resetAt) {
|
|
11
|
+
const fresh = { count: 1, resetAt: now + windowMs };
|
|
12
|
+
hits.set(key, fresh);
|
|
13
|
+
return fresh;
|
|
14
|
+
}
|
|
15
|
+
entry.count++;
|
|
16
|
+
return entry;
|
|
17
|
+
},
|
|
18
|
+
cleanup() {
|
|
19
|
+
const now = Date.now();
|
|
20
|
+
for (const [key, value] of hits) {
|
|
21
|
+
if (now > value.resetAt)
|
|
22
|
+
hits.delete(key);
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
const DEFAULT_EXCLUDE = ["/_next", "/favicon.ico", "/api/health"];
|
|
28
|
+
/**
|
|
29
|
+
* Extract the client address from a `x-forwarded-for` list.
|
|
30
|
+
*
|
|
31
|
+
* Each proxy *appends* the address it saw, so the list reads
|
|
32
|
+
* `client-supplied, …, nearest-hop`. With `trustProxy` trusted proxies the real
|
|
33
|
+
* client sits `trustProxy` entries from the right, which is index
|
|
34
|
+
* `entries.length - trustProxy`:
|
|
35
|
+
*
|
|
36
|
+
* - `trustProxy: 0` — index `length`, i.e. out of range. Nothing is trusted, so
|
|
37
|
+
* there is no entry we can attribute to the client rather than to a proxy.
|
|
38
|
+
* - `trustProxy: 1` — `"9.9.9.1, 1.1.1.1"` gives index 1, the real client, and
|
|
39
|
+
* `9.9.9.1` (the attacker's) is correctly ignored.
|
|
40
|
+
* - `trustProxy: 2` — `"9.9.9.1, 1.1.1.1, 10.0.0.1"` gives index 1 again.
|
|
41
|
+
*
|
|
42
|
+
* Returns `undefined` when the list is absent or shorter than the trust depth,
|
|
43
|
+
* because in that case every entry present was chosen by the client.
|
|
44
|
+
*/
|
|
45
|
+
export function forwardedClientIp(headerValue, trustProxy) {
|
|
46
|
+
if (!headerValue)
|
|
47
|
+
return undefined;
|
|
48
|
+
const entries = headerValue
|
|
49
|
+
.split(",")
|
|
50
|
+
.map((entry) => entry.trim())
|
|
51
|
+
.filter(Boolean);
|
|
52
|
+
if (entries.length === 0)
|
|
53
|
+
return undefined;
|
|
54
|
+
const index = entries.length - trustProxy;
|
|
55
|
+
if (index < 0)
|
|
56
|
+
return undefined;
|
|
57
|
+
return entries[index];
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Next.js middleware for rate limiting AI API routes.
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```ts
|
|
64
|
+
* // middleware.ts
|
|
65
|
+
* import { hilbrasMiddleware } from "@hilbras/sdk/nextjs/edge";
|
|
66
|
+
*
|
|
67
|
+
* export const config = { matcher: ["/api/:path*"] };
|
|
68
|
+
* export default hilbrasMiddleware({ maxRequests: 30, trustProxy: 1 });
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export function hilbrasMiddleware(options = {}) {
|
|
72
|
+
const { maxRequests = 60, windowSeconds = 60, excludePaths = DEFAULT_EXCLUDE, onError, trustProxy = 0, fallbackKey, store = createMemoryStore(), } = options;
|
|
73
|
+
function getClientKey(request) {
|
|
74
|
+
const fromHeader = forwardedClientIp(request.headers.get("x-forwarded-for"), trustProxy);
|
|
75
|
+
if (fromHeader)
|
|
76
|
+
return fromHeader;
|
|
77
|
+
// `x-real-ip` is written by the proxy rather than derived from the client's
|
|
78
|
+
// header chain, so it is a better fallback — but only when at least one
|
|
79
|
+
// proxy is trusted.
|
|
80
|
+
if (trustProxy > 0) {
|
|
81
|
+
const realIp = request.headers.get("x-real-ip")?.trim();
|
|
82
|
+
if (realIp)
|
|
83
|
+
return realIp;
|
|
84
|
+
}
|
|
85
|
+
const explicit = fallbackKey?.(request);
|
|
86
|
+
if (explicit)
|
|
87
|
+
return explicit;
|
|
88
|
+
// Deliberately not `request.ip`: Next.js derives it from the forwarded
|
|
89
|
+
// headers in exactly the way `trustProxy` exists to correct, so trusting it
|
|
90
|
+
// here would reintroduce the spoof.
|
|
91
|
+
//
|
|
92
|
+
// Collapsing everything unidentifiable into one bucket is the safe
|
|
93
|
+
// direction: it can under-serve anonymous callers, but it cannot hand an
|
|
94
|
+
// attacker a fresh budget by omitting a header.
|
|
95
|
+
return "unidentified";
|
|
96
|
+
}
|
|
97
|
+
return async function middleware(request) {
|
|
98
|
+
const path = request.nextUrl.pathname;
|
|
99
|
+
if (excludePaths.some((p) => path.startsWith(p))) {
|
|
100
|
+
return NextResponse.next();
|
|
101
|
+
}
|
|
102
|
+
await store.cleanup?.();
|
|
103
|
+
const key = `${getClientKey(request)}:${path}`;
|
|
104
|
+
const { count, resetAt } = await store.hit(key, windowSeconds * 1000);
|
|
105
|
+
if (count > maxRequests) {
|
|
106
|
+
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000);
|
|
107
|
+
if (onError)
|
|
108
|
+
return onError("Rate limit exceeded");
|
|
109
|
+
return NextResponse.json({ error: "Rate limit exceeded", retryAfter }, { status: 429, headers: { "Retry-After": String(retryAfter) } });
|
|
110
|
+
}
|
|
111
|
+
return NextResponse.next();
|
|
112
|
+
};
|
|
113
|
+
}
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* - useCompletion: Text completion hook
|
|
15
15
|
*/
|
|
16
16
|
export { createServerClient, ServerHilbrasClient, type ServerClientOptions } from "./server.js";
|
|
17
|
+
export type { FrameworkErrorContext, FrameworkHandlerLimits, FrameworkRequestContext, } from "../shared/handler-core.js";
|
|
17
18
|
export { createChatHandler, createCompletionHandler, type ChatRequest, type ChatResponse } from "./route-handlers.js";
|
|
18
19
|
export { useChat, type UseChatOptions, type UseChatReturn } from "./use-chat.js";
|
|
19
20
|
export { useCompletion, type UseCompletionOptions, type UseCompletionReturn } from "./use-completion.js";
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Next.js runtime surface
|
|
3
|
+
*
|
|
4
|
+
* Minimal structural types for the pieces of `next/server` these helpers use.
|
|
5
|
+
*
|
|
6
|
+
* The SDK cannot import from `next/server`: `next` is an optional peer
|
|
7
|
+
* dependency, and the published package must typecheck and build in a project
|
|
8
|
+
* that has never installed Next. Declaring the surface here keeps the build
|
|
9
|
+
* self-contained.
|
|
10
|
+
*
|
|
11
|
+
* Every member below is structurally satisfied by the real Next types, so a
|
|
12
|
+
* Next `NextRequest`/`NextResponse` is assignable to these without a cast, and
|
|
13
|
+
* a real Next route accepts a handler typed against them. That is the whole
|
|
14
|
+
* point of declaring the *shape* rather than the nominal class.
|
|
15
|
+
*/
|
|
16
|
+
/** The subset of `NextRequest` the helpers read. */
|
|
17
|
+
export interface HilbrasNextRequest {
|
|
18
|
+
/** Parse the body as JSON. Present on the Web `Request`. */
|
|
19
|
+
json(): Promise<unknown>;
|
|
20
|
+
/** Abort signal for a client disconnect. */
|
|
21
|
+
readonly signal: AbortSignal;
|
|
22
|
+
/** Incoming headers. */
|
|
23
|
+
readonly headers: Headers;
|
|
24
|
+
/** Path of the matched route, e.g. `/api/chat`. */
|
|
25
|
+
readonly nextUrl: {
|
|
26
|
+
readonly pathname: string;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Next-resolved client IP.
|
|
30
|
+
*
|
|
31
|
+
* Deliberately never read by the middleware: Next derives this from the
|
|
32
|
+
* forwarded headers, which is the value `trustProxy` exists to correct.
|
|
33
|
+
*/
|
|
34
|
+
readonly ip?: string;
|
|
35
|
+
}
|
|
36
|
+
/** The subset of `NextResponse` the helpers produce. */
|
|
37
|
+
export interface HilbrasNextResponse {
|
|
38
|
+
json(body: unknown, init?: {
|
|
39
|
+
status?: number;
|
|
40
|
+
headers?: Record<string, string>;
|
|
41
|
+
}): HilbrasNextResponse;
|
|
42
|
+
next(init?: unknown): HilbrasNextResponse;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A Next middleware request, typed structurally.
|
|
46
|
+
*
|
|
47
|
+
* A real `NextRequest` satisfies this: it extends the Web `Request`, so it has
|
|
48
|
+
* `json`, `signal` and `headers`, and Next adds `nextUrl` and `ip`.
|
|
49
|
+
*/
|
|
50
|
+
export type NextRequestLike = HilbrasNextRequest;
|
|
51
|
+
/**
|
|
52
|
+
* Build the minimal `NextResponse` surface at runtime.
|
|
53
|
+
*
|
|
54
|
+
* `NextResponse.json` and `NextResponse.next` return objects that the Next
|
|
55
|
+
* runtime converts into a real response. Outside Next — in a unit test, or in
|
|
56
|
+
* an app using the Web `Response` — the standard constructors do the same job,
|
|
57
|
+
* so they are used as the fallback and keep the SDK free of a hard Next
|
|
58
|
+
* dependency at runtime too.
|
|
59
|
+
*/
|
|
60
|
+
export declare function createNextResponseShim(): {
|
|
61
|
+
json: HilbrasNextResponse["json"];
|
|
62
|
+
next: HilbrasNextResponse["next"];
|
|
63
|
+
};
|