@juspay/neurolink 13.8.30 → 13.9.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.
@@ -10,14 +10,39 @@
10
10
  * names its own files. Neither suits a request that arrived over a socket.
11
11
  *
12
12
  * So the proxy resolves every reference itself and hands the SDK nothing but
13
- * `data:` URIs and downloaded bytes:
14
- * - `data:` URIs pass through untouched, they carry their own content;
13
+ * images it has checked:
14
+ * - `data:` URIs carry their own content. The payload is decoded strictly (an
15
+ * alphabet, length or padding no decoder takes is refused) and its leading
16
+ * bytes must be a recognised image, whatever the URI says it is. The SDK is
17
+ * handed `data:<detected type>;base64,<standard payload>`: the type comes
18
+ * from the bytes, never from the client, so a JPEG labelled `image/png`
19
+ * reaches the provider as `image/jpeg`;
15
20
  * - `https://` URLs are downloaded with the same helper the agent routes use
16
21
  * (`resolveAgentInput` -> `safeDownload`): redirects refused, addresses
17
- * checked, size capped;
18
- * - everything else (local paths, `http://`, `file://`, any other scheme) is
19
- * refused before the file system or the network is touched, so the answer
20
- * for a path that exists and one that does not is the same.
22
+ * checked, size capped. The bytes must then be a recognised image too, or
23
+ * the URL is refused, so a page that answers `200 text/html` is never sent
24
+ * on as a picture. The SDK reads the type of those bytes itself, from the
25
+ * same signatures;
26
+ * - everything else (local paths, `http://`, `file://`, any other scheme, an
27
+ * empty string) is refused before the file system or the network is
28
+ * touched, so the answer for a path that exists and one that does not is the
29
+ * same.
30
+ *
31
+ * An image slot that carries nothing is refused too, never skipped. The doors
32
+ * hand over what the client sent: an empty `data:` payload (an OpenAI
33
+ * `data:image/png;base64,`, a Claude `base64` source or a Gemini `inlineData`
34
+ * of an image type whose `data` is empty or absent) is `invalid_image_data`, and
35
+ * an empty URL (an OpenAI `image_url.url` or a Claude `url` source) is
36
+ * `invalid_image_reference`.
37
+ *
38
+ * "A recognised image" is a file signature (`sniffInputImageMimeType`): PNG,
39
+ * JPEG, WebP and GIF, which every provider takes, and HEIC, HEIF, AVIF, BMP,
40
+ * TIFF, ICO and JPEG 2000, which no provider except Google (HEIC and HEIF only)
41
+ * takes. The SDK tries to convert those seven to PNG before dispatch, for every
42
+ * provider, Google included; when neither sharp nor ffmpeg can read the file it
43
+ * sends the original bytes under the detected type. SVG is markup and is
44
+ * refused. Nothing in the proxy decodes the picture: a body that is corrupt
45
+ * after a valid signature is the provider's to refuse.
21
46
  *
22
47
  * Unlike the agent routes there is no allowed-roots setting: the proxy listens
23
48
  * on loopback without credentials by default, and a path allow-list on a server
@@ -36,10 +61,52 @@
36
61
  * @module proxy/proxyImageInput
37
62
  */
38
63
  import { AgentInputError, resolveAgentInput, } from "../server/utils/agentInput.js";
64
+ import { sniffInputImageMimeType } from "../utils/imageDetection.js";
39
65
  import { logger } from "../utils/logger.js";
40
66
  import { ProxyContextPreflightError } from "./proxyContextPreflight.js";
41
67
  const INVALID_REFERENCE_MESSAGE = "Image references must be data: URIs or public https URLs. Local file paths, http URLs and other schemes are not accepted by this proxy.";
42
68
  const UNFETCHABLE_URL_MESSAGE = "An image URL could not be fetched. It must be a public https URL, answer without a redirect and fit the size limit.";
69
+ const INVALID_IMAGE_DATA_MESSAGE = "An inline image is not a recognised image. Send the bytes of a PNG, JPEG, WebP, GIF, HEIC, HEIF, AVIF, BMP, TIFF, ICO or JPEG 2000 image as base64, in a data: URI.";
70
+ const INVALID_URL_CONTENT_MESSAGE = "An image URL did not serve a recognised image. It must serve the bytes of a PNG, JPEG, WebP, GIF, HEIC, HEIF, AVIF, BMP, TIFF, ICO or JPEG 2000 image.";
71
+ /**
72
+ * Base64 characters sufficient for the longest signature probe: every format is
73
+ * recognised within its first few dozen bytes, and an ISO-BMFF `ftyp` box can
74
+ * list brands for a little longer. A multiple of four, so the prefix of a longer
75
+ * payload decodes without padding.
76
+ */
77
+ const SNIFF_BASE64_CHARS = 1024;
78
+ /** The longest `data:...;base64` header taken for one; a longer one is no header. */
79
+ const MAX_DATA_URI_HEADER_CHARS = 256;
80
+ /** Standard or URL-safe base64, the two alphabets Google's JSON `bytes` fields accept. */
81
+ const BASE64_TEXT = /^[A-Za-z0-9+/_-]+={0,2}$/;
82
+ /**
83
+ * `data` as padded standard-alphabet base64, which is what a `data:` URI carries,
84
+ * or undefined when it is not well-formed base64.
85
+ *
86
+ * The SDK forwards the base64 text of a `data:` URI to the provider as it is, so
87
+ * a URL-safe or unpadded payload would reach a provider that expects neither.
88
+ * The alphabet check alone lets through a payload no decoder takes: one
89
+ * character over a multiple of four is no base64 length at all, and padding
90
+ * must be exactly what the length calls for. An empty string is not base64.
91
+ *
92
+ * One rule for every door: the Gemini parser applies it before wrapping raw
93
+ * `inlineData`, and the vetter applies it again to every `data:` URI it is given.
94
+ */
95
+ export function toStandardBase64(data) {
96
+ if (!BASE64_TEXT.test(data)) {
97
+ return undefined;
98
+ }
99
+ const standard = /[-_]/.test(data)
100
+ ? data.replace(/-/g, "+").replace(/_/g, "/")
101
+ : data;
102
+ const body = standard.replace(/=+$/, "");
103
+ const padding = standard.length - body.length;
104
+ const missing = (4 - (body.length % 4)) % 4;
105
+ if (missing === 3 || (padding > 0 && padding !== missing)) {
106
+ return undefined;
107
+ }
108
+ return `${body}${"=".repeat(missing)}`;
109
+ }
43
110
  /** An image reference the proxy refuses; answers 400 in the client's format. */
44
111
  export class ProxyImageInputError extends ProxyContextPreflightError {
45
112
  constructor(code, message) {
@@ -57,6 +124,9 @@ function describeRefusal(entry) {
57
124
  if (typeof entry !== "string") {
58
125
  return "non-string";
59
126
  }
127
+ if (entry === "") {
128
+ return "empty";
129
+ }
60
130
  if (/^https?:\/\//i.test(entry)) {
61
131
  return "http-url";
62
132
  }
@@ -71,6 +141,67 @@ function refuseReference(entry) {
71
141
  });
72
142
  return new ProxyImageInputError("invalid_image_reference", INVALID_REFERENCE_MESSAGE);
73
143
  }
144
+ /**
145
+ * `reason` names which check failed, for the operator's log; the data itself is
146
+ * never logged, nor echoed to the client.
147
+ */
148
+ function refuseImageData(reason, message = INVALID_IMAGE_DATA_MESSAGE) {
149
+ logger.warn("[proxy] refused image bytes that are not a recognised image", {
150
+ reason,
151
+ });
152
+ return new ProxyImageInputError("invalid_image_data", message);
153
+ }
154
+ /** A declared type safe to put in a log line; anything else is `malformed`. */
155
+ const loggableType = (declared) => declared.length <= 64 && /^[\w./+-]*$/.test(declared)
156
+ ? declared.toLowerCase()
157
+ : "malformed";
158
+ /**
159
+ * Check one `data:` URI and return it as `data:<detected type>;base64,<payload>`.
160
+ *
161
+ * The header's parameters and declared type are discarded: the type is read
162
+ * from the decoded bytes. Only the leading bytes are decoded to find it; the
163
+ * rest of the payload has been checked as base64 text and is forwarded as is.
164
+ *
165
+ * @throws {ProxyImageInputError} `invalid_image_data` when the URI is not a
166
+ * base64 data URI, its payload is empty or not strict base64, or its bytes are
167
+ * not a recognised image.
168
+ */
169
+ function verifyInlineImage(entry) {
170
+ const comma = entry.indexOf(",");
171
+ if (comma === -1 || comma > MAX_DATA_URI_HEADER_CHARS) {
172
+ throw refuseImageData("data-uri-shape");
173
+ }
174
+ const header = entry.slice("data:".length, comma);
175
+ if (!/;base64$/i.test(header)) {
176
+ throw refuseImageData("data-uri-shape");
177
+ }
178
+ if (comma + 1 === entry.length) {
179
+ throw refuseImageData("empty-payload");
180
+ }
181
+ const payload = toStandardBase64(entry.slice(comma + 1));
182
+ if (payload === undefined) {
183
+ throw refuseImageData("not-base64");
184
+ }
185
+ const detected = sniffInputImageMimeType(Buffer.from(payload.slice(0, SNIFF_BASE64_CHARS), "base64"));
186
+ if (detected === null) {
187
+ throw refuseImageData("not-an-image");
188
+ }
189
+ const declared = header.slice(0, header.indexOf(";"));
190
+ if (declared.toLowerCase() !== detected) {
191
+ logger.debug("[proxy] corrected the declared type of an inline image", {
192
+ declared: loggableType(declared),
193
+ detected,
194
+ });
195
+ }
196
+ return `data:${detected};base64,${payload}`;
197
+ }
198
+ /** The bytes of a downloaded image, or a refusal when they are not one. */
199
+ function verifyDownloadedImage(bytes) {
200
+ if (sniffInputImageMimeType(bytes) === null) {
201
+ throw refuseImageData("url-content", INVALID_URL_CONTENT_MESSAGE);
202
+ }
203
+ return bytes;
204
+ }
74
205
  function asProxyImageInputError(error) {
75
206
  if (!(error instanceof AgentInputError)) {
76
207
  return error;
@@ -83,14 +214,23 @@ function asProxyImageInputError(error) {
83
214
  return new ProxyImageInputError("image_url_unfetchable", UNFETCHABLE_URL_MESSAGE);
84
215
  }
85
216
  /**
86
- * Resolve one list of client image references to what the SDK may be given.
217
+ * Resolve one list of client image references to what the SDK may be given:
218
+ * `data:` URIs rewritten to carry the type their bytes have, and downloaded
219
+ * bytes that are an image.
220
+ *
221
+ * Inline images are judged before anything is downloaded, so a request already
222
+ * doomed by one costs no network. Size and count are judged on the `data:` URIs
223
+ * as the client sent them (their string length), then on the downloads (their
224
+ * bytes), exactly as the agent routes judge them.
87
225
  *
88
226
  * `signal` cancels the work: a download in flight is aborted and no further
89
227
  * reference is started. A cancellation rejects with the signal's own error, not
90
228
  * with a {@link ProxyImageInputError}, since nothing was refused.
91
229
  *
92
- * @throws {ProxyImageInputError} for the first reference that is refused, or
93
- * for a list that carries too many images or too many bytes.
230
+ * @throws {ProxyImageInputError} for the first reference that is refused
231
+ * (`invalid_image_reference`, `invalid_image_data`, `image_url_unfetchable`),
232
+ * or for a list that carries too many images or too many bytes
233
+ * (`image_input_too_large`).
94
234
  */
95
235
  export async function vetProxyImages(images, signal) {
96
236
  const references = [];
@@ -100,9 +240,21 @@ export async function vetProxyImages(images, signal) {
100
240
  }
101
241
  references.push(entry);
102
242
  }
243
+ const inline = references.map((entry) => isDataUri(entry) ? verifyInlineImage(entry) : undefined);
103
244
  try {
245
+ // The client's own strings are what is measured against the limits; the
246
+ // rewritten ones replace them afterwards.
104
247
  const resolved = await resolveAgentInput({ text: "", images: references }, { signal });
105
- return resolved.images ?? [];
248
+ return (resolved.images ?? []).map((item, index) => {
249
+ const verified = inline[index];
250
+ if (verified !== undefined) {
251
+ return verified;
252
+ }
253
+ if (typeof item === "string") {
254
+ throw refuseReference(item);
255
+ }
256
+ return verifyDownloadedImage(item);
257
+ });
106
258
  }
107
259
  catch (error) {
108
260
  throw asProxyImageInputError(error);
@@ -83,6 +83,9 @@ export class BaseServerAdapter extends EventEmitter {
83
83
  "Content-Type",
84
84
  "Authorization",
85
85
  "X-Request-ID",
86
+ // The session middleware's default header: without it a browser
87
+ // client on another origin could not send it.
88
+ "X-Session-Id",
86
89
  ],
87
90
  credentials: config.cors?.credentials ?? false,
88
91
  maxAge: config.cors?.maxAge ?? 86400,
@@ -36,6 +36,7 @@ export { createCompressionMiddleware, createErrorHandlingMiddleware, createLoggi
36
36
  export { createDeprecationMiddleware } from "./middleware/deprecation.js";
37
37
  export { createMCPBodyAttachmentMiddleware, fastifyMCPBodyHook, } from "./middleware/mcpBodyAttachment.js";
38
38
  export { createRateLimitMiddleware, createSlidingWindowRateLimitMiddleware, InMemoryRateLimitStore, } from "./middleware/rateLimit.js";
39
+ export { createSessionMiddleware } from "./middleware/session.js";
39
40
  export { CommonSchemas, createFieldValidator, createRequestValidationMiddleware, ValidationError, } from "./middleware/validation.js";
40
41
  export { AgentExecuteRequestSchema as OpenAPIAgentExecuteRequestSchema, AgentExecuteResponseSchema, AgentInputSchema, ApiKeySecurityScheme, BasicSecurityScheme, BearerSecurityScheme, CommonParameters, ConversationMessageSchema, createApiInfo, createDeleteOperation, createErrorResponse as createOpenAPIErrorResponse, createGetOperation, createHeaderParameter, createOpenAPIGenerator, createPathParameter, createPostOperation, createQueryParameter, createServer as createOpenAPIServer, createStreamingPostOperation, createStreamingResponse, createSuccessResponse, DefaultServers, ErrorResponseSchema, generateOpenAPIFromConfig, generateOpenAPISpec, HealthResponseSchema, MCPServerStatusSchema, MCPServersListResponseSchema, MCPServerToolSchema, MetricsResponseSchema, NeuroLinkApiInfo, OpenAPIGenerator, OpenAPISchemas, ProviderInfoSchema, ReadyResponseSchema, SessionSchema, SessionsListResponseSchema, StandardErrorResponses, StandardTags, TokenUsageSchema, ToolCallSchema, ToolDefinitionSchema, ToolExecuteRequestSchema as OpenAPIToolExecuteRequestSchema, ToolExecuteResponseSchema, ToolListResponseSchema, ToolParameterSchema, } from "./openapi/index.js";
41
42
  export { createAgentRoutes, createAllRoutes, createHealthRoutes, createMCPRoutes, createMemoryRoutes, createOpenApiRoutes, createToolRoutes, createTranscribeRoutes, registerAllRoutes, createClaudeProxyRoutes, createOpenAIProxyRoutes, createCodexProxyRoutes, createGeminiProxyRoutes, } from "./routes/index.js";
@@ -79,6 +79,7 @@ export { createCompressionMiddleware, createErrorHandlingMiddleware, createLoggi
79
79
  export { createDeprecationMiddleware } from "./middleware/deprecation.js";
80
80
  export { createMCPBodyAttachmentMiddleware, fastifyMCPBodyHook, } from "./middleware/mcpBodyAttachment.js";
81
81
  export { createRateLimitMiddleware, createSlidingWindowRateLimitMiddleware, InMemoryRateLimitStore, } from "./middleware/rateLimit.js";
82
+ export { createSessionMiddleware } from "./middleware/session.js";
82
83
  export { CommonSchemas, createFieldValidator, createRequestValidationMiddleware, ValidationError, } from "./middleware/validation.js";
83
84
  // ============================================
84
85
  // OpenAPI
@@ -5,6 +5,7 @@
5
5
  export { createAuthMiddleware } from "./auth.js";
6
6
  export { createCacheMiddleware } from "./cache.js";
7
7
  export { createRateLimitMiddleware } from "./rateLimit.js";
8
+ export { createSessionMiddleware } from "./session.js";
8
9
  export { createRequestValidationMiddleware } from "./validation.js";
9
10
  export { createTimingMiddleware, createRequestIdMiddleware, createErrorHandlingMiddleware, createSecurityHeadersMiddleware, createLoggingMiddleware, createCompressionMiddleware, } from "./common.js";
10
11
  export { createAbortSignalMiddleware, createExpressAbortMiddleware, } from "./abortSignal.js";
@@ -5,6 +5,7 @@
5
5
  export { createAuthMiddleware } from "./auth.js";
6
6
  export { createCacheMiddleware } from "./cache.js";
7
7
  export { createRateLimitMiddleware } from "./rateLimit.js";
8
+ export { createSessionMiddleware } from "./session.js";
8
9
  export { createRequestValidationMiddleware } from "./validation.js";
9
10
  export { createTimingMiddleware, createRequestIdMiddleware, createErrorHandlingMiddleware, createSecurityHeadersMiddleware, createLoggingMiddleware, createCompressionMiddleware, } from "./common.js";
10
11
  export { createAbortSignalMiddleware, createExpressAbortMiddleware, } from "./abortSignal.js";
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Session Middleware
3
+ * Sets `ctx.session` from a header (or cookie) and scopes it to the
4
+ * authenticated user.
5
+ */
6
+ import type { MiddlewareDefinition, ServerSessionConfig } from "../../types/index.js";
7
+ /**
8
+ * Create session middleware.
9
+ *
10
+ * Reads a session id from `X-Session-Id` (or the configured header) and sets
11
+ * `ctx.session.id`. When the header is absent or empty and `cookieName` is set,
12
+ * that cookie supplies the id instead. When a user is authenticated the id
13
+ * becomes `<urlencoded-userId>~<id>`, so two users who send the same id get
14
+ * different sessions: the in-memory conversation manager keys sessions by id
15
+ * alone, and without the prefix one user could read and extend another's
16
+ * conversation by guessing its id. The delimiter is `~` rather than `:`,
17
+ * because Redis session ids and the perUserAuth memory routes reject `:`. A
18
+ * request with no id gets no session.
19
+ *
20
+ * The prefix isolates the conversations the agent routes keep. It is not an
21
+ * access check on the memory routes. Without `perUserAuth` they look a session
22
+ * up by the id in the URL (on the in-memory manager by that id alone, on Redis
23
+ * by it together with the `userId` query parameter), so a caller who can reach
24
+ * them and knows a prefixed id such as `bob~chat-1` reads that session unless
25
+ * the server prevents it. With `perUserAuth` they are scoped to the caller and
26
+ * refuse a session id that contains `:`. The `~` form this middleware writes
27
+ * is accepted there, so a session it created can be listed, read and deleted
28
+ * through the memory routes as well as used through the agent routes.
29
+ *
30
+ * The prefix also relies on `ctx.user` naming one person: when every client
31
+ * shares one credential they share one `ctx.user`, and one prefix.
32
+ *
33
+ * The server must carry middleware state for this to do anything. By default
34
+ * (`carryMiddlewareState` off) Express, Fastify and Koa build a fresh context
35
+ * for every middleware step and for the handler, so this middleware sees no
36
+ * `ctx.user` and the `ctx.session` it sets never reaches the handler; Hono
37
+ * shares the context only for a request whose client sent its own
38
+ * `X-Request-ID`. Nothing warns about it. `registerAllRoutes()` with
39
+ * `perUserAuth` turns the carry on for the server; otherwise create the server
40
+ * with `carryMiddlewareState: true`.
41
+ *
42
+ * With `perUserAuth` on the routes, the agent routes take the session only from
43
+ * `ctx.session`, and only for an authenticated request, so this middleware is
44
+ * how a signed-in client keeps a conversation. A request with no `ctx.user`
45
+ * (optional authentication) gets no conversation even when it sends an id, so
46
+ * anonymous callers never share one.
47
+ *
48
+ * With `perUserAuth` off (the default) the agent routes take the session from the
49
+ * request body and this middleware has no effect on them, whether
50
+ * `carryMiddlewareState` is off (the handler never receives `ctx.session`) or on
51
+ * (it does, and the routes do not read it); with the carry on it still sets
52
+ * `ctx.session` for your own routes. That holds on Express, Fastify and Koa, and
53
+ * on Hono when the client sent no `X-Request-ID`. The exception is a context that
54
+ * did not receive the adapters' carry: Hono when the client sent its own
55
+ * `X-Request-ID` (with the carry on or off), an adapter you wrote, or a handler
56
+ * called directly. There an authenticated user's session is `ctx.session` alone
57
+ * (the body's is ignored), and an anonymous caller's is `ctx.session`, else the
58
+ * body's, so anonymous callers that send the same id share one bare
59
+ * conversation.
60
+ *
61
+ * The agent routes keep a conversation only when conversation memory is
62
+ * enabled on the `NeuroLink` instance; without it nothing is remembered
63
+ * whatever the session id.
64
+ *
65
+ * A browser client on another origin must be allowed to send the header. The
66
+ * default `X-Session-Id` is in the servers' default CORS allowed headers. A
67
+ * custom `headerName` is not: add it to `cors.headers`, which replaces the
68
+ * default list when you set it. A cookie sent cross-origin also needs
69
+ * `cors.credentials: true` and a listed origin rather than `*`.
70
+ *
71
+ * Ids start with a letter or digit and continue with letters, digits, `.`, `_`
72
+ * or `-`, 128 characters at most. A header that is not valid is a 400. A
73
+ * cookie that is not valid is ignored, as if absent: a browser sends it on its
74
+ * own, so it must not turn every request into an error.
75
+ *
76
+ * Register it after authentication. The registration order is what runs: the
77
+ * `order` number (12, with auth at 10) is informational and nothing sorts by
78
+ * it, so a session middleware registered before authentication sees no user and
79
+ * sets an unprefixed id without any warning.
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * const neurolink = new NeuroLink({ conversationMemory: { enabled: true } });
84
+ * const server = await createServer(neurolink, { framework: "hono" });
85
+ * server.registerMiddleware(createAuthMiddleware({ type: "bearer", validate }));
86
+ * server.registerMiddleware(createSessionMiddleware());
87
+ * // perUserAuth also turns on carryMiddlewareState for this server.
88
+ * registerAllRoutes(server, "/api", { perUserAuth: true });
89
+ * // A client sends `X-Session-Id: chat-1`; the agent routes then keep that
90
+ * // conversation, separately for each authenticated user.
91
+ * ```
92
+ */
93
+ export declare function createSessionMiddleware(config?: ServerSessionConfig): MiddlewareDefinition;
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Session Middleware
3
+ * Sets `ctx.session` from a header (or cookie) and scopes it to the
4
+ * authenticated user.
5
+ */
6
+ import { ValidationError } from "../errors.js";
7
+ /**
8
+ * What a caller may name a session: short, starting with a letter or digit, and
9
+ * with no `~`, so the user prefix added below can never be spoofed by a crafted
10
+ * id. `:` is also refused: Redis session ids and the perUserAuth memory routes
11
+ * reject it, and a requested id must be usable as that segment as well as an
12
+ * in-memory map key.
13
+ */
14
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
15
+ const SESSION_ID_MESSAGE = "session id must be 1 to 128 characters: a letter or digit, then letters, digits, '.', '_' or '-'";
16
+ /**
17
+ * Join an authenticated user and a requested session id into one map key.
18
+ *
19
+ * `:` cannot appear: Redis `getSessionKey` and the perUserAuth memory routes
20
+ * reject it, so `<userId>:<id>` is listed by GET /memory/sessions but cannot
21
+ * be read or stored on Redis. `~` cannot appear in a requested id, and
22
+ * `encodeURIComponent` plus an extra `~` → `%7E` pass keeps it out of the
23
+ * user segment, including multi-tenant ids such as `cust:merchant:shop`.
24
+ */
25
+ function scopedSessionId(userId, requested) {
26
+ const user = encodeURIComponent(userId).replaceAll("~", "%7E");
27
+ return `${user}~${requested}`;
28
+ }
29
+ function readHeader(headers, name) {
30
+ const wanted = name.toLowerCase();
31
+ for (const [key, value] of Object.entries(headers)) {
32
+ if (key.toLowerCase() === wanted) {
33
+ return value;
34
+ }
35
+ }
36
+ return undefined;
37
+ }
38
+ function withSession(ctx, requested, next) {
39
+ ctx.session = {
40
+ id: ctx.user ? scopedSessionId(ctx.user.id, requested) : requested,
41
+ };
42
+ return next();
43
+ }
44
+ function readCookie(headers, name) {
45
+ const raw = readHeader(headers, "cookie");
46
+ if (!raw) {
47
+ return undefined;
48
+ }
49
+ for (const part of raw.split(";")) {
50
+ const separator = part.indexOf("=");
51
+ if (separator > 0 && part.slice(0, separator).trim() === name) {
52
+ try {
53
+ return decodeURIComponent(part.slice(separator + 1).trim());
54
+ }
55
+ catch {
56
+ return part.slice(separator + 1).trim();
57
+ }
58
+ }
59
+ }
60
+ return undefined;
61
+ }
62
+ /**
63
+ * Create session middleware.
64
+ *
65
+ * Reads a session id from `X-Session-Id` (or the configured header) and sets
66
+ * `ctx.session.id`. When the header is absent or empty and `cookieName` is set,
67
+ * that cookie supplies the id instead. When a user is authenticated the id
68
+ * becomes `<urlencoded-userId>~<id>`, so two users who send the same id get
69
+ * different sessions: the in-memory conversation manager keys sessions by id
70
+ * alone, and without the prefix one user could read and extend another's
71
+ * conversation by guessing its id. The delimiter is `~` rather than `:`,
72
+ * because Redis session ids and the perUserAuth memory routes reject `:`. A
73
+ * request with no id gets no session.
74
+ *
75
+ * The prefix isolates the conversations the agent routes keep. It is not an
76
+ * access check on the memory routes. Without `perUserAuth` they look a session
77
+ * up by the id in the URL (on the in-memory manager by that id alone, on Redis
78
+ * by it together with the `userId` query parameter), so a caller who can reach
79
+ * them and knows a prefixed id such as `bob~chat-1` reads that session unless
80
+ * the server prevents it. With `perUserAuth` they are scoped to the caller and
81
+ * refuse a session id that contains `:`. The `~` form this middleware writes
82
+ * is accepted there, so a session it created can be listed, read and deleted
83
+ * through the memory routes as well as used through the agent routes.
84
+ *
85
+ * The prefix also relies on `ctx.user` naming one person: when every client
86
+ * shares one credential they share one `ctx.user`, and one prefix.
87
+ *
88
+ * The server must carry middleware state for this to do anything. By default
89
+ * (`carryMiddlewareState` off) Express, Fastify and Koa build a fresh context
90
+ * for every middleware step and for the handler, so this middleware sees no
91
+ * `ctx.user` and the `ctx.session` it sets never reaches the handler; Hono
92
+ * shares the context only for a request whose client sent its own
93
+ * `X-Request-ID`. Nothing warns about it. `registerAllRoutes()` with
94
+ * `perUserAuth` turns the carry on for the server; otherwise create the server
95
+ * with `carryMiddlewareState: true`.
96
+ *
97
+ * With `perUserAuth` on the routes, the agent routes take the session only from
98
+ * `ctx.session`, and only for an authenticated request, so this middleware is
99
+ * how a signed-in client keeps a conversation. A request with no `ctx.user`
100
+ * (optional authentication) gets no conversation even when it sends an id, so
101
+ * anonymous callers never share one.
102
+ *
103
+ * With `perUserAuth` off (the default) the agent routes take the session from the
104
+ * request body and this middleware has no effect on them, whether
105
+ * `carryMiddlewareState` is off (the handler never receives `ctx.session`) or on
106
+ * (it does, and the routes do not read it); with the carry on it still sets
107
+ * `ctx.session` for your own routes. That holds on Express, Fastify and Koa, and
108
+ * on Hono when the client sent no `X-Request-ID`. The exception is a context that
109
+ * did not receive the adapters' carry: Hono when the client sent its own
110
+ * `X-Request-ID` (with the carry on or off), an adapter you wrote, or a handler
111
+ * called directly. There an authenticated user's session is `ctx.session` alone
112
+ * (the body's is ignored), and an anonymous caller's is `ctx.session`, else the
113
+ * body's, so anonymous callers that send the same id share one bare
114
+ * conversation.
115
+ *
116
+ * The agent routes keep a conversation only when conversation memory is
117
+ * enabled on the `NeuroLink` instance; without it nothing is remembered
118
+ * whatever the session id.
119
+ *
120
+ * A browser client on another origin must be allowed to send the header. The
121
+ * default `X-Session-Id` is in the servers' default CORS allowed headers. A
122
+ * custom `headerName` is not: add it to `cors.headers`, which replaces the
123
+ * default list when you set it. A cookie sent cross-origin also needs
124
+ * `cors.credentials: true` and a listed origin rather than `*`.
125
+ *
126
+ * Ids start with a letter or digit and continue with letters, digits, `.`, `_`
127
+ * or `-`, 128 characters at most. A header that is not valid is a 400. A
128
+ * cookie that is not valid is ignored, as if absent: a browser sends it on its
129
+ * own, so it must not turn every request into an error.
130
+ *
131
+ * Register it after authentication. The registration order is what runs: the
132
+ * `order` number (12, with auth at 10) is informational and nothing sorts by
133
+ * it, so a session middleware registered before authentication sees no user and
134
+ * sets an unprefixed id without any warning.
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * const neurolink = new NeuroLink({ conversationMemory: { enabled: true } });
139
+ * const server = await createServer(neurolink, { framework: "hono" });
140
+ * server.registerMiddleware(createAuthMiddleware({ type: "bearer", validate }));
141
+ * server.registerMiddleware(createSessionMiddleware());
142
+ * // perUserAuth also turns on carryMiddlewareState for this server.
143
+ * registerAllRoutes(server, "/api", { perUserAuth: true });
144
+ * // A client sends `X-Session-Id: chat-1`; the agent routes then keep that
145
+ * // conversation, separately for each authenticated user.
146
+ * ```
147
+ */
148
+ export function createSessionMiddleware(config = {}) {
149
+ const { headerName = "X-Session-Id", cookieName, skipPaths = [] } = config;
150
+ return {
151
+ name: "session",
152
+ // Informational: the adapters run middleware in registration order, so
153
+ // this only reads correctly when it is registered after authentication.
154
+ order: 12,
155
+ excludePaths: skipPaths,
156
+ handler: async (ctx, next) => {
157
+ // An empty header counts as absent, so the opted-in cookie can still
158
+ // supply the id.
159
+ const header = readHeader(ctx.headers, headerName);
160
+ if (header !== undefined && header !== "") {
161
+ if (!SESSION_ID_PATTERN.test(header)) {
162
+ throw new ValidationError([{ field: headerName, message: SESSION_ID_MESSAGE }], ctx.requestId);
163
+ }
164
+ return withSession(ctx, header, next);
165
+ }
166
+ const cookie = cookieName
167
+ ? readCookie(ctx.headers, cookieName)
168
+ : undefined;
169
+ if (cookie !== undefined && SESSION_ID_PATTERN.test(cookie)) {
170
+ return withSession(ctx, cookie, next);
171
+ }
172
+ return next();
173
+ },
174
+ };
175
+ }
@@ -0,0 +1,29 @@
1
+ # Proxy pool engines (src/lib/server/routes)
2
+
3
+ Loaded automatically when working under `src/lib/server/routes/`. Moved out of the root CLAUDE.md.
4
+
5
+ The proxy runs two independent subscription pool engines that share the token
6
+ store and the cooldown/quota persistence layer:
7
+
8
+ | | Anthropic (Claude) | Codex (ChatGPT) |
9
+ | ------------------ | ------------------------------- | ----------------------------------------- |
10
+ | Inbound route | `POST /v1/messages` | `POST /backend-api/codex/responses` |
11
+ | Upstream | `api.anthropic.com/v1/messages` | `chatgpt.com/backend-api/codex/responses` |
12
+ | Wire format | Anthropic Messages | OpenAI Responses |
13
+ | Token-store prefix | `anthropic:` | `codex:` |
14
+ | Quota windows | unified 5h / 7d | primary / secondary |
15
+
16
+ Both engines key **cooldowns** and **quota** by the full account key
17
+ (`anthropic:foo`, `codex:foo`). The Anthropic side used to key quota by the bare
18
+ label (`foo`), and snapshots saved that way are still in
19
+ `~/.neurolink/account-quotas.json` on users' machines, so it reads
20
+ `persisted[account.key] ?? persisted[account.label]` and writes under
21
+ `account.key`: a legacy snapshot is picked up, and replaced on the next save.
22
+ `codex:foo` cannot collide with a bare Anthropic label, because no bare label
23
+ contains a `:` prefix. Use the full key in new code, and keep the label fallback
24
+ when reading Anthropic quota until the legacy snapshots are gone.
25
+
26
+ When adding a third provider, follow the Codex pattern: a new
27
+ `<provider>OAuth.ts`, a `<provider>AccountUsage.ts` quota parser, and a
28
+ `<provider>ProxyRoutes.ts` engine — do not modify the Anthropic hot path.
29
+ See `docs/features/codex-proxy-support.md`.
@@ -115,7 +115,12 @@ export type CORSConfig = {
115
115
  origins?: string[];
116
116
  /** Allowed HTTP methods */
117
117
  methods?: string[];
118
- /** Allowed headers */
118
+ /**
119
+ * Allowed request headers. Default `Content-Type`, `Authorization`,
120
+ * `X-Request-ID` and `X-Session-Id`. A list you pass replaces the default, it
121
+ * is not added to it, so keep the ones your clients send, and add the header
122
+ * name of a custom `createSessionMiddleware({ headerName })`.
123
+ */
119
124
  headers?: string[];
120
125
  /** Allow credentials */
121
126
  credentials?: boolean;
@@ -486,7 +491,12 @@ export type RouteGroup = {
486
491
  export type MiddlewareDefinition = {
487
492
  /** Middleware name */
488
493
  name: string;
489
- /** Execution order (lower = earlier) */
494
+ /**
495
+ * Where this middleware belongs relative to the others, for reading and for
496
+ * the debug log. Informational only: the adapters do not sort by it, they run
497
+ * middleware in the order it was registered. The built-ins' numbers (for
498
+ * example authentication 10, session 12) say what to register first.
499
+ */
490
500
  order?: number;
491
501
  /** Middleware handler */
492
502
  handler: MiddlewareHandler;
@@ -1171,6 +1181,34 @@ export type ServerValidationResult<T> = {
1171
1181
  error: ErrorResponse;
1172
1182
  data?: undefined;
1173
1183
  };
1184
+ /**
1185
+ * Session middleware configuration
1186
+ *
1187
+ * The middleware only has an effect on a server that carries middleware state
1188
+ * (`ServerAdapterConfig.carryMiddlewareState`, which `registerAllRoutes()`
1189
+ * turns on when given `perUserAuth`); without it the handler does not see the
1190
+ * session it sets, except on Hono for a request whose client sent its own
1191
+ * `X-Request-ID`, which shares one context with the handler either way (with
1192
+ * `perUserAuth` off, the agent routes can then use that session).
1193
+ */
1194
+ export type ServerSessionConfig = {
1195
+ /**
1196
+ * Header that carries the session id (default: "X-Session-Id"). A header
1197
+ * holding an invalid id is a 400; an empty one counts as absent. The default
1198
+ * is in the servers' default CORS allowed headers; a different name is not,
1199
+ * so a browser client on another origin needs it added to `cors.headers`.
1200
+ */
1201
+ headerName?: string;
1202
+ /**
1203
+ * Cookie that carries the session id, read when the header is absent or
1204
+ * empty. Off by default: a cookie is sent by the browser on its own, so
1205
+ * enabling it is the operator's decision. A cookie holding an invalid id is
1206
+ * ignored, as if absent, rather than failing the request.
1207
+ */
1208
+ cookieName?: string;
1209
+ /** Skip the middleware for certain paths */
1210
+ skipPaths?: string[];
1211
+ };
1174
1212
  /**
1175
1213
  * Authentication configuration
1176
1214
  */