@juspay/neurolink 13.8.31 → 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.
- package/CHANGELOG.md +3 -5
- package/dist/browser/neurolink.min.js +306 -306
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/server/abstract/baseServerAdapter.js +3 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -0
- package/dist/server/middleware/index.d.ts +1 -0
- package/dist/server/middleware/index.js +1 -0
- package/dist/server/middleware/session.d.ts +93 -0
- package/dist/server/middleware/session.js +175 -0
- package/dist/types/server.d.ts +40 -2
- package/docs-site/static/search-index.json +17 -8
- package/package.json +2 -1
package/dist/index.d.ts
CHANGED
|
@@ -460,7 +460,7 @@ export { DEFAULT_COMPACTION_THRESHOLD, resolveHistoryBudget, } from "./context/b
|
|
|
460
460
|
* await server.start();
|
|
461
461
|
* ```
|
|
462
462
|
*/
|
|
463
|
-
export { AgentExecuteRequestSchema, AlreadyRunningError, BaseServerAdapter, ConfigurationError, createAgentRoutes, createAgentWebSocketHandler, createAllRoutes, createAuthMiddleware, createCacheInvalidator, createCacheMiddleware, createCompressionMiddleware, createDataStreamResponse, createDataStreamWriter, createErrorHandlingMiddleware, createErrorResponse, createFieldValidator, createHealthRoutes, createLoggingMiddleware, createMCPRoutes, createMemoryRoutes, createNDJSONHeaders, createOpenAPIGenerator, createRateLimitMiddleware, createRequestIdMiddleware, createRequestValidationMiddleware, createRoleMiddleware, createSecurityHeadersMiddleware, createServer, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes, ErrorCategory, ErrorRecoveryStrategies, ErrorSeverity, ExpressServerAdapter, FastifyServerAdapter, generateOpenAPIFromConfig, generateOpenAPISpec, HandlerError, HonoServerAdapter, InMemoryCacheStore, InMemoryRateLimitStore, InvalidAuthenticationError, KoaServerAdapter, MissingDependencyError, NotRunningError, pipeAsyncIterableToDataStream, RouteConflictError, RouteNotFoundError, registerAllRoutes, ServerAdapterError, ServerAdapterErrorCode, ServerAdapterFactory, ServerAuthenticationError, ServerAuthorizationError, ServerNameParamSchema, ServerRateLimitError, ServerStartError, ServerStopError, ServerTimeoutError, ServerValidationError, SessionIdParamSchema, StreamAbortedError, StreamingError, ToolArgumentsSchema, ToolExecuteRequestSchema, ToolNameParamSchema, ToolSearchQuerySchema, ValidationError, validateParams, validateQuery, validateRequest, WebSocketConnectionError, WebSocketConnectionManager, WebSocketError, WebSocketMessageRouter, wrapError, } from "./server/index.js";
|
|
463
|
+
export { AgentExecuteRequestSchema, AlreadyRunningError, BaseServerAdapter, ConfigurationError, createAgentRoutes, createAgentWebSocketHandler, createAllRoutes, createAuthMiddleware, createCacheInvalidator, createCacheMiddleware, createCompressionMiddleware, createDataStreamResponse, createDataStreamWriter, createErrorHandlingMiddleware, createErrorResponse, createFieldValidator, createHealthRoutes, createLoggingMiddleware, createMCPRoutes, createMemoryRoutes, createNDJSONHeaders, createOpenAPIGenerator, createRateLimitMiddleware, createRequestIdMiddleware, createRequestValidationMiddleware, createRoleMiddleware, createSecurityHeadersMiddleware, createServer, createSessionMiddleware, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes, ErrorCategory, ErrorRecoveryStrategies, ErrorSeverity, ExpressServerAdapter, FastifyServerAdapter, generateOpenAPIFromConfig, generateOpenAPISpec, HandlerError, HonoServerAdapter, InMemoryCacheStore, InMemoryRateLimitStore, InvalidAuthenticationError, KoaServerAdapter, MissingDependencyError, NotRunningError, pipeAsyncIterableToDataStream, RouteConflictError, RouteNotFoundError, registerAllRoutes, ServerAdapterError, ServerAdapterErrorCode, ServerAdapterFactory, ServerAuthenticationError, ServerAuthorizationError, ServerNameParamSchema, ServerRateLimitError, ServerStartError, ServerStopError, ServerTimeoutError, ServerValidationError, SessionIdParamSchema, StreamAbortedError, StreamingError, ToolArgumentsSchema, ToolExecuteRequestSchema, ToolNameParamSchema, ToolSearchQuerySchema, ValidationError, validateParams, validateQuery, validateRequest, WebSocketConnectionError, WebSocketConnectionManager, WebSocketError, WebSocketMessageRouter, wrapError, } from "./server/index.js";
|
|
464
464
|
/**
|
|
465
465
|
* @deprecated Use `ServerTimeoutError` instead — renamed to end the naming
|
|
466
466
|
* collision with the canonical `utils/timeout.ts` `TimeoutError`. Kept as an
|
package/dist/index.js
CHANGED
|
@@ -701,7 +701,7 @@ createAuthMiddleware, createCacheInvalidator, createCacheMiddleware, createCompr
|
|
|
701
701
|
// Streaming
|
|
702
702
|
createDataStreamWriter, createErrorHandlingMiddleware, createErrorResponse, createFieldValidator, createHealthRoutes, createLoggingMiddleware, createMCPRoutes, createMemoryRoutes, createNDJSONHeaders, createOpenAPIGenerator, createRateLimitMiddleware, createRequestIdMiddleware, createRequestValidationMiddleware, createRoleMiddleware, createSecurityHeadersMiddleware,
|
|
703
703
|
// Server Factory
|
|
704
|
-
createServer, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes,
|
|
704
|
+
createServer, createSessionMiddleware, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes,
|
|
705
705
|
// Error Constants
|
|
706
706
|
ErrorCategory, ErrorRecoveryStrategies, ErrorSeverity, ExpressServerAdapter, FastifyServerAdapter, generateOpenAPIFromConfig, generateOpenAPISpec, HandlerError, HonoServerAdapter, InMemoryCacheStore, InMemoryRateLimitStore, InvalidAuthenticationError, KoaServerAdapter, MissingDependencyError, NotRunningError,
|
|
707
707
|
// OpenAPI
|
|
@@ -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,
|
package/dist/server/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/server/index.js
CHANGED
|
@@ -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
|
+
}
|
package/dist/types/server.d.ts
CHANGED
|
@@ -115,7 +115,12 @@ export type CORSConfig = {
|
|
|
115
115
|
origins?: string[];
|
|
116
116
|
/** Allowed HTTP methods */
|
|
117
117
|
methods?: string[];
|
|
118
|
-
/**
|
|
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
|
-
/**
|
|
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
|
*/
|
|
@@ -7960,9 +7960,9 @@
|
|
|
7960
7960
|
{"objectID":"f3ed50a8afe14efb53c7029170f8bfe943eac05f70b247ba01d53b27d9e7ccd2","title":"Production Checklist","url":"/docs/guides/server-adapters/koa#production-checklist","content":"[ ] Configure environment variables securely\n[ ] Set appropriate CORS origins (not *)\n[ ] Enable rate limiting with reasonable limits\n[ ] Add authentication middleware\n[ ] Configure request timeouts\n[ ] Set body size limits\n[ ] Enable compression middleware\n[ ] Add security headers (koa-helmet)\n[ ] Configure logging with appropriate level\n[ ] Set up health check monitoring\n[ ] Configure error tracking (Sentry, etc.)\n[ ] Use process manager (PM2) for production","hierarchy":{"lvl0":"Guides","lvl1":"Koa Adapter","lvl2":"Production Checklist","lvl3":""}},
|
|
7961
7961
|
{"objectID":"a8c9927bcf1e3a824cfa9b91cd734c74faeab471578e658bdc06aef74d298957","title":"Related Documentation","url":"/docs/guides/server-adapters/koa#related-documentation","content":"Server Adapters Overview - Getting started with server adapters\nHono Adapter - Recommended framework for most use cases\nExpress Adapter - Compare with Express adapter\nSecurity Best Practices - Authentication patterns\nDeployment Guide - Production deployment strategies","hierarchy":{"lvl0":"Guides","lvl1":"Koa Adapter","lvl2":"Related Documentation","lvl3":""}},
|
|
7962
7962
|
{"objectID":"abda958c7148cc510ffd8fd63fc0e95f2261198d73957c24cd05bf43f24f54d4","title":"Additional Resources","url":"/docs/guides/server-adapters/koa#additional-resources","content":"Koa Documentation - Official Koa documentation\nKoa Wiki - Community resources and middleware list\n@koa/router - Router middleware documentation\n\nNeed Help? Join our GitHub Discussions or open an issue.","hierarchy":{"lvl0":"Guides","lvl1":"Koa Adapter","lvl2":"Additional Resources","lvl3":""}},
|
|
7963
|
-
{"objectID":"55417289121a6d70296ad2b754304f12a3d3a469e5eba572acaadd6e76c8a010","title":"Middleware Reference","url":"/docs/guides/server-adapters/middleware","content":"Middleware Reference\n\nNeuroLink server adapters provide a comprehensive set of middleware components for common server operations. All middleware follows a consistent pattern and can be composed together for your specific use case.\n\nMiddleware Overview\n\n| Middleware | Purpose | Order |\n| ------------------------------------- | ----------------------------------------- | ----- |\n| createTimingMiddleware() | Measures request duration | 0 |\n| createRequestIdMiddleware() | Generates/propagates request IDs | 0 |\n| createErrorHandlingMiddleware() | Centralized error catching and formatting | 1 |\n| createSecurityHeadersMiddleware() | Adds security headers | 2 |\n| createLoggingMiddleware() | Request/response logging | 3 |\n| createRateLimitMiddleware() | Rate limiting | 5 |\n| createAbortSignalMiddleware() | Client disconnection detection | 5 |\n| createCompressionMiddleware() | Response compression signaling | 5 |\n| createAuthMiddleware() | Authentication | 10 |\n| createRequestValidationMiddleware() | Request body/query/params validation | 15 |\n| createCacheMiddleware() | Response caching | 20 |\n| createMCPBodyAttachmentMiddleware() | MCP SDK body compatibility | 10 |\n| createDeprecationMiddleware() | RFC 8594 deprecation headers | 100 |\n\nThe order value
|
|
7963
|
+
{"objectID":"55417289121a6d70296ad2b754304f12a3d3a469e5eba572acaadd6e76c8a010","title":"Middleware Reference","url":"/docs/guides/server-adapters/middleware","content":"Middleware Reference\n\nNeuroLink server adapters provide a comprehensive set of middleware components for common server operations. All middleware follows a consistent pattern and can be composed together for your specific use case.\n\nMiddleware Overview\n\n| Middleware | Purpose | Order |\n| ------------------------------------- | ----------------------------------------- | ----- |\n| createTimingMiddleware() | Measures request duration | 0 |\n| createRequestIdMiddleware() | Generates/propagates request IDs | 0 |\n| createErrorHandlingMiddleware() | Centralized error catching and formatting | 1 |\n| createSecurityHeadersMiddleware() | Adds security headers | 2 |\n| createLoggingMiddleware() | Request/response logging | 3 |\n| createRateLimitMiddleware() | Rate limiting | 5 |\n| createAbortSignalMiddleware() | Client disconnection detection | 5 |\n| createCompressionMiddleware() | Response compression signaling | 5 |\n| createAuthMiddleware() | Authentication | 10 |\n| createSessionMiddleware() | Sets ctx.session, scoped to the user | 12 |\n| createRequestValidationMiddleware() | Request body/query/params validation | 15 |\n| createCacheMiddleware() | Response caching | 20 |\n| createMCPBodyAttachmentMiddleware() | MCP SDK body compatibility | 10 |\n| createDeprecationMiddleware() | RFC 8594 deprecation headers | 100 |\n\nThe order value is informational: the server runs middleware in the order you register it, not by this number. Register the middleware with the lower number first, so that authentication runs before anything that reads the user.\n\nTiming Middleware\n\nMeasures request duration and adds timing headers to responses.\n\nUsage\n\nHeaders Set\n\n| Header | Description | Example |\n| ----------------- | -------------------------------------------------------- | ----------------- |\n| X-Response-Time | Total request processing time in milliseconds | 45.23ms |\n| Server-Timing | Standard Server-Timing header for performance monitoring | total;dur=45.23 |\n\nWhen to Use\nAlways recommended for production servers\nEssential for performance monitoring and debugging\nWorks with browser Developer Tools and APM systems\n\nRequest ID Middleware\n\nEnsures every request has a unique identifier for tracing and debugging.\n\nConfiguration\n\nUsage\n\nHeaders\n\n| Header | Direction | Description |\n| -------------- | --------- | ----------------------------------------------- |\n| X-Request-ID | Request | Propagates existing ID from client (if present) |\n| X-Request-ID | Response | Returns request ID for client-side correlation |\n\nWhen to Use\nAlways recommended for production servers\nEssential for distributed tracing\nEnables log correlation across services\nHelps with debugging and support tickets\n\nError Handling Middleware\n\nCatches errors and formats them consistently across all routes.\n\nConfiguration\n\nUsage\n\nError Response Format\n\nWhen to Use\nAlways recommended for production servers\nProvides consistent error responses\nPrevents leaking sensitive information in production\nEnable stack traces only in development\n\nSecurity Headers Middleware\n\nAdds common security headers to protect against various web vulnerabilities.\n\nConfiguration\n\nUsage\n\nHeaders Set\n\n| Header | Default Value | Description |\n| --------------------------- | ------------------------------------- | ----------------------------- |\n| X-Frame-Options | DENY | Prevents clickjacking |\n| X-Content-Type-Options | nosniff | Prevents MIME sniffing |\n| Strict-Transport-Security | max-age=31536000; includeSubDomains | Enforces HTTPS |\n| Referrer-Policy | strict-origin-when-cross-origin | Controls referrer information |\n| X-XSS-Protection | 1; mode=block | Legacy XSS protection |\n| Content-Security-Policy | Not set by default | Content security policy |\n\nWhen to Use\nAlways recommended for production servers\nRequired for security compliance (OWASP, PCI-DSS)\nConfigure CSP based on your application needs\nDisable HSTS initially if not ready for HTTPS-only\n\nLogging Middleware\n\nLogs request and response information with configurable detail levels.\n\nConfiguration\n\nUsage\n\nLog Output\n\nRequest Log:\n\nResponse Log:\n\nError Log:\n\nWhen to Use\nAlways recommended for production servers\nDisable body logging in production for performance and privacy\nUse ","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"","lvl3":""}},
|
|
7964
7964
|
{"objectID":"85c17d817c6a2684c64cc765cb4063caad35b5c9fb934d56e6a07a9042a7c605","title":"Middleware Reference","url":"/docs/guides/server-adapters/middleware#middleware-reference","content":"NeuroLink server adapters provide a comprehensive set of middleware components for common server operations. All middleware follows a consistent pattern and can be composed together for your specific use case.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Middleware Reference","lvl3":""}},
|
|
7965
|
-
{"objectID":"2e55beb234a0ba6d06a3a796603ba196b8c566bd4d21f3ae90c309f8e895c68d","title":"Middleware Overview","url":"/docs/guides/server-adapters/middleware#middleware-overview","content":"| Middleware | Purpose | Order |\n| ------------------------------------- | ----------------------------------------- | ----- |\n| createTimingMiddleware() | Measures request duration | 0 |\n| createRequestIdMiddleware() | Generates/propagates request IDs | 0 |\n| createErrorHandlingMiddleware() | Centralized error catching and formatting | 1 |\n| createSecurityHeadersMiddleware() | Adds security headers | 2 |\n| createLoggingMiddleware() | Request/response logging | 3 |\n| createRateLimitMiddleware() | Rate limiting | 5 |\n| createAbortSignalMiddleware() | Client disconnection detection | 5 |\n| createCompressionMiddleware() | Response compression signaling | 5 |\n| createAuthMiddleware() | Authentication | 10 |\n| createRequestValidationMiddleware() | Request body/query/params validation | 15 |\n| createCacheMiddleware() | Response caching | 20 |\n| createMCPBodyAttachmentMiddleware() | MCP SDK body compatibility | 10 |\n| createDeprecationMiddleware() | RFC 8594 deprecation headers | 100 |\n\nThe order value
|
|
7965
|
+
{"objectID":"2e55beb234a0ba6d06a3a796603ba196b8c566bd4d21f3ae90c309f8e895c68d","title":"Middleware Overview","url":"/docs/guides/server-adapters/middleware#middleware-overview","content":"| Middleware | Purpose | Order |\n| ------------------------------------- | ----------------------------------------- | ----- |\n| createTimingMiddleware() | Measures request duration | 0 |\n| createRequestIdMiddleware() | Generates/propagates request IDs | 0 |\n| createErrorHandlingMiddleware() | Centralized error catching and formatting | 1 |\n| createSecurityHeadersMiddleware() | Adds security headers | 2 |\n| createLoggingMiddleware() | Request/response logging | 3 |\n| createRateLimitMiddleware() | Rate limiting | 5 |\n| createAbortSignalMiddleware() | Client disconnection detection | 5 |\n| createCompressionMiddleware() | Response compression signaling | 5 |\n| createAuthMiddleware() | Authentication | 10 |\n| createSessionMiddleware() | Sets ctx.session, scoped to the user | 12 |\n| createRequestValidationMiddleware() | Request body/query/params validation | 15 |\n| createCacheMiddleware() | Response caching | 20 |\n| createMCPBodyAttachmentMiddleware() | MCP SDK body compatibility | 10 |\n| createDeprecationMiddleware() | RFC 8594 deprecation headers | 100 |\n\nThe order value is informational: the server runs middleware in the order you register it, not by this number. Register the middleware with the lower number first, so that authentication runs before anything that reads the user.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Middleware Overview","lvl3":""}},
|
|
7966
7966
|
{"objectID":"dea1350a158d30abea4a8fa4f9fb8332d17897c73848dfc17dfcb8ef67d212a8","title":"Timing Middleware","url":"/docs/guides/server-adapters/middleware#timing-middleware","content":"Measures request duration and adds timing headers to responses.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Timing Middleware","lvl3":""}},
|
|
7967
7967
|
{"objectID":"ef0e2e6f086491b64279f24a0018e9d61c713c77983e6f2bf4d9e37f702367b9","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage","content":"Usage","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
|
|
7968
7968
|
{"objectID":"6de1035c7a2fd89803a0093b22d725a20248e74f4c2d4238d07a2f5dad98f9e4","title":"Headers Set","url":"/docs/guides/server-adapters/middleware#headers-set","content":"| Header | Description | Example |\n| ----------------- | -------------------------------------------------------- | ----------------- |\n| X-Response-Time | Total request processing time in milliseconds | 45.23ms |\n| Server-Timing | Standard Server-Timing header for performance monitoring | total;dur=45.23 |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Headers Set","lvl3":""}},
|
|
@@ -8020,18 +8020,27 @@
|
|
|
8020
8020
|
{"objectID":"dc019f0ad08d89054d4f68945d6855bbc6d74da0b3f8082e35f56fa5f731ec51","title":"Headers Read","url":"/docs/guides/server-adapters/middleware#headers-read","content":"| Header | Auth Type | Description |\n| --------------- | ------------- | ------------------------------------ |\n| Authorization | bearer, basic | Bearer <token> or Basic <base64> |\n| X-API-Key | api-key | Raw API key value |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Headers Read","lvl3":""}},
|
|
8021
8021
|
{"objectID":"43776c9da774387f221eb7918931d5a4a59b42c949ef248c30c7afb5512ee7ea","title":"Dev Playground Support","url":"/docs/guides/server-adapters/middleware#dev-playground-support","content":"Requests with an X-NeuroLink-Dev-Playground: true (or X-NeuroLink-Playground: true) header bypass authentication and receive a default developer user context (id: \"playground\", roles: [\"developer\"]), but only when NODE_ENV is exactly development. The variable is read on every request.\n\nWith NODE_ENV unset, production, test, staging or any other value, the header is ignored and the request must carry a valid credential. The bypass is therefore off by default in a deployment that never sets NODE_ENV. Pass skipDevPlayground: false to refuse the header even in development.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Dev Playground Support","lvl3":""}},
|
|
8022
8022
|
{"objectID":"a2d39b213dc8603fb3d7889b019eebc14f3705eb13b1185d7f98bf26d988f4aa","title":"When to Use","url":"/docs/guides/server-adapters/middleware#when-to-use-10","content":"Protecting API endpoints\nUser identification and authorization\nRate limiting by user\nAudit logging","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"When to Use","lvl3":""}},
|
|
8023
|
-
{"objectID":"
|
|
8023
|
+
{"objectID":"961a2c37220a3779b5bb23e6a2a8d360f928344af801a021f6d714754e2a9e5e","title":"Session Middleware","url":"/docs/guides/server-adapters/middleware#session-middleware","content":"Sets ctx.session from a header (or an opt-in cookie) and scopes it to the authenticated user. Register it after authentication, on a server that carries middleware state.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Session Middleware","lvl3":""}},
|
|
8024
|
+
{"objectID":"d2deb08c40f7fc9a32db9d4b2fd251656728c465d71632f4ee15e761652ce04c","title":"The server must carry middleware state","url":"/docs/guides/server-adapters/middleware#the-server-must-carry-middleware-state","content":"The middleware sets ctx.session on the context of its own step, and it prefixes the id with the user that authentication put on the context of an earlier step. Both only work if the server carries middleware state, which is off by default (carryMiddlewareState, see Carrying middleware state). With it off, Express, Fastify and Koa build a fresh context for every middleware step and for the handler, so the session middleware sees no ctx.user and the ctx.session it sets is gone before the handler runs; Hono shares one context only for a request whose client sent its own X-Request-ID. Apart from that Hono case, a server without the carry therefore gets no sessions from this middleware, and nothing warns about it.\n\nThere are two ways to turn the carry on:\nregisterAllRoutes(server, \"/api\", { perUserAuth: true }) turns it on for the server, which is what the usage example below relies on.\ncreateServer(neurolink, { framework, config: { carryMiddlewareState: true } }) turns it on directly. Use it when your own routes read ctx.session, or when you register the routes yourself instead of with registerAllRoutes.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"The server must carry middleware state","lvl3":""}},
|
|
8025
|
+
{"objectID":"0509f1acb589a9fd8e4fbce928f8b5e04d7ab2b0ba93f2f40eef1e03a230ecde","title":"How it relates to perUserAuth","url":"/docs/guides/server-adapters/middleware#how-it-relates-to-peruserauth","content":"Whether the agent routes (/agent/execute, /agent/stream) trust the request body's sessionId depends on perUserAuth (see the security guide):\n\n| perUserAuth | Session the agent routes use |\n| -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| true | Only ctx.session, and only for an authenticated request; a body sessionId is ignored. registerAllRoutes turns the carry on for this mode. This middleware is how a signed-in client keeps a conversation, and without it there is no memory |\n| true, anonymous | None. A request with no ctx.user (optional authentication) gets no conversation even when it sends X-Session-Id, so anonymous callers never share one |\n| false (default) | The body's sessionId.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"How it relates to perUserAuth","lvl3":""}},
|
|
8024
8026
|
{"objectID":"5030f1bc68100ad92c3ab2b6bafbbb96c9069b282976e5233f3dc1cafdf62811","title":"Configuration","url":"/docs/guides/server-adapters/middleware#configuration-9","content":"Configuration","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Configuration","lvl3":""}},
|
|
8025
|
-
{"objectID":"0e7a4984ab1818dc1207c2dffcaebfdc635a483d79f89525da8359a301c4652e","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage-11","content":"
|
|
8027
|
+
{"objectID":"0e7a4984ab1818dc1207c2dffcaebfdc635a483d79f89525da8359a301c4652e","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage-11","content":"A client sends X-Session-Id: chat-1; the agent routes then keep that conversation, separately for each signed-in user. Without conversationMemory enabled on the NeuroLink instance nothing is remembered, whatever the session id. registerAllRoutes also mounts the memory routes, and perUserAuth scopes them to the caller as well; they list, read and delete the conversations this middleware creates (see What the user prefix does and does not isolate).\n\nRegister the session middleware after authentication. The server runs middleware in registration order, and the order: 12 of this middleware is informational. Registered before authentication, it sees no user and sets the bare, unprefixed id; nothing warns about it. The same holds on a server that does not carry middleware state: there the middleware sees no user whatever the order, and the handler gets no session at all.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
|
|
8028
|
+
{"objectID":"2eff85cff358391e531f7222a46944f23fc08f676d6ade582e8ba98d3295d415","title":"Behaviour","url":"/docs/guides/server-adapters/middleware#behaviour","content":"| Request | ctx.session.id |\n| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |\n| Authenticated, header chat-1 | <urlencoded-userId>~chat-1, so two users who send chat-1 get different conversations |\n| Not authenticated, header chat-1 | chat-1 (the agent routes ignore it under perUserAuth: true) |\n| No header, or an empty one (and no cookie configured) | not set; no session |\n| No header or an empty one, cookieName set, cookie holds a valid id | the cookie's id, prefixed like a header's |\n| cookieName set, cookie holds an invalid id | the cookie is ignored, as if absent; no session |\n| Header that is not a valid id | 400 |\n\nA valid id is 1 to 128 characters: the first is a letter or digit, the rest are letters, digits, ., _ or -. An id that starts with ., _ or -, or contains :, is not valid.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Behaviour","lvl3":""}},
|
|
8029
|
+
{"objectID":"094629bc45431759611f6c3d97481975303ad413b0d82cf94a36fe7eee97a4af","title":"What the user prefix does and does not isolate","url":"/docs/guides/server-adapters/middleware#what-the-user-prefix-does-and-does-not-isolate","content":"The prefix keeps the conversations the agent routes hold apart: the in-memory conversation manager keys sessions by id alone, so without it one user could read and extend another's conversation by guessing its id. Requested ids contain no ~, so a crafted id cannot imitate another user's prefix. The delimiter is ~ rather than : because Redis session ids and the perUserAuth memory routes reject :.\n\nIt is not an access check on the memory routes. Without perUserAuth they look a session up by the id in the URL: on the in-memory manager by that id alone, on Redis by it together with the userId query parameter. Whether a server limits them to a session's owner then depends on how that server protects those routes, not on this middleware, so a caller who can reach them and knows a prefixed id such as bob~chat-1 reads that session unless the server prevents it. With perUserAuth the memory routes are scoped to the caller (see the security guide), and they refuse a session id that contains :. The ~ form this middleware writes is accepted, so a session it created can be listed, read and deleted through those routes. Memory routes report the prefixed id; treat it as opaque.\n\nThe prefix also depends on ctx.user naming one person. When every client shares one credential (one API key), they share one ctx.user and so one prefix, and the prefix does not tell them apart.\n\nUnder perUserAuth: true an anonymous request (optional authentication) is given no session by the agent routes at all, because with a bare id every anonymous caller that sent the same X-Session-Id would share one conversation. If anonymous callers need a conversation, keep perUserAuth off, where they choose it with a body sessionId (this middleware's id is ignored there except on Hono with the caller's own X-Request-ID, see the table above), or have them sign in.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"What the user prefix does and does not isolate","lvl3":""}},
|
|
8030
|
+
{"objectID":"085efce0ee14472c104cec33ac4ca0b7fe6260cb73f1c9bfc3ed907a1cec58b4","title":"Browser clients and CORS","url":"/docs/guides/server-adapters/middleware#browser-clients-and-cors","content":"A page on another origin can send the header only if the server's CORS allowed headers list it. The default list is Content-Type, Authorization, X-Request-ID and X-Session-Id, so the default header works once the page's origin is in cors.origins.\n\nA custom headerName is not in that list. Add it to cors.headers, and note that a list you pass replaces the default rather than extending it, so keep the others your clients send:\n\nA cookie read through cookieName is sent by the browser only when the page asks for credentials, which also needs cors.credentials: true and an explicit origin in cors.origins rather than *.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Browser clients and CORS","lvl3":""}},
|
|
8031
|
+
{"objectID":"2ae4cb64298f85a7c201fa225bebeb309ffa947d8012d2ffdeddc00c823ab5ee","title":"Header and cookie","url":"/docs/guides/server-adapters/middleware#header-and-cookie","content":"The header wins when both are present. A header that is present but empty counts as absent, so the cookie can still supply the id. A header holding an invalid id is a 400, because the client chose to send it. A cookie holding an invalid id is ignored instead: a browser sends cookies on its own, so a stale or foreign cookie that happens to share the name must not turn every route into a 400. cookieName is off by default for the same reason: a cookie is sent without the client choosing to, so enabling it is the operator's decision.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Header and cookie","lvl3":""}},
|
|
8032
|
+
{"objectID":"fb39a14f946d17f7771143d4e3c349bc51999e8aa360456371d0b8dec29a6449","title":"Request Validation Middleware","url":"/docs/guides/server-adapters/middleware#request-validation-middleware","content":"Provides schema-based request validation for body, query, params, and headers.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Request Validation Middleware","lvl3":""}},
|
|
8033
|
+
{"objectID":"66088f57d128691ad8eb333d1513c66a038336eb42d8c726d7171f2d42247df3","title":"Configuration","url":"/docs/guides/server-adapters/middleware#configuration-10","content":"Configuration","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Configuration","lvl3":""}},
|
|
8034
|
+
{"objectID":"40b5f0e3313c653f8721d60f18454928e5856afdd764174a10af91ee17244b2a","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage-12","content":"Usage","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
|
|
8026
8035
|
{"objectID":"684bd819b68b5b0ca6711c9939bac94634efa74953166704af156b4df91261f3","title":"Error Response Format","url":"/docs/guides/server-adapters/middleware#error-response-format-1","content":"Error Response Format","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Error Response Format","lvl3":""}},
|
|
8027
8036
|
{"objectID":"82758f32126cb9af5f9e25763494cfdbba464d89d977e292be0ad93ce5407717","title":"Common Schemas","url":"/docs/guides/server-adapters/middleware#common-schemas","content":"Pre-built schemas for common validation patterns:\n\n| Schema | Fields |\n| ------------ | ----------------------------- |\n| uuid | UUID string format |\n| email | Email string format |\n| pagination | page, limit, offset |\n| sorting | sortBy, sortOrder |\n| idParam | Required id parameter |\n| dateRange | startDate, endDate |\n| search | q (query), fields (array) |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Common Schemas","lvl3":""}},
|
|
8028
8037
|
{"objectID":"c987ce4f64a434aa882c45de83d62bbd957349a779c0fb52f4984c6c75eb6a9a","title":"When to Use","url":"/docs/guides/server-adapters/middleware#when-to-use-11","content":"Input sanitization and security\nAPI contract enforcement\nEarly error detection\nDocumentation generation (with OpenAPI)","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"When to Use","lvl3":""}},
|
|
8029
8038
|
{"objectID":"2d237896d0d0c4ed79ebc68e174c410558908188e6d515458a1a8417f3b02f10","title":"Cache Middleware","url":"/docs/guides/server-adapters/middleware#cache-middleware","content":"Provides response caching with LRU eviction and configurable TTL.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Cache Middleware","lvl3":""}},
|
|
8030
|
-
{"objectID":"
|
|
8031
|
-
{"objectID":"
|
|
8039
|
+
{"objectID":"2cc6a8453d17b365558fb6a604b32c3813eb4279dabae222041233bd717f9303","title":"Configuration","url":"/docs/guides/server-adapters/middleware#configuration-11","content":"Configuration","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Configuration","lvl3":""}},
|
|
8040
|
+
{"objectID":"72ab6d4eae18b3dbf4dddd251e1b9a3e39357bf07e3d17a934b4f69d03534977","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage-13","content":"Usage","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
|
|
8032
8041
|
{"objectID":"1ac8f000d65b645f6f77bcd02d6db61215a071d411e56db06f0f690d49eb1700","title":"Headers Set","url":"/docs/guides/server-adapters/middleware#headers-set-4","content":"| Header | Value | Description |\n| --------------- | ------------ | ----------------------------------- |\n| X-Cache | HIT | Response served from cache |\n| X-Cache | MISS | Response freshly generated |\n| X-Cache-Age | 45 | Seconds since cached (only on HIT) |\n| Cache-Control | max-age=60 | Browser caching directive (on MISS) |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Headers Set","lvl3":""}},
|
|
8033
8042
|
{"objectID":"75f9986be54ffb5b39930d9b1514e6a696e982fe41bbc2a600033e3254bad57b","title":"When to Use","url":"/docs/guides/server-adapters/middleware#when-to-use-12","content":"Expensive operations (database queries, AI generation)\nFrequently requested static data\nRate limit budget optimization\nReducing latency for repeated requests","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"When to Use","lvl3":""}},
|
|
8034
|
-
{"objectID":"3e522465420d38d5c0e20166dfc374452a7c8366d592ff2cf3a9cb9afadc3b7d","title":"Composing Middleware","url":"/docs/guides/server-adapters/middleware#composing-middleware","content":"Middleware
|
|
8043
|
+
{"objectID":"3e522465420d38d5c0e20166dfc374452a7c8366d592ff2cf3a9cb9afadc3b7d","title":"Composing Middleware","url":"/docs/guides/server-adapters/middleware#composing-middleware","content":"Middleware run in the order they are registered (the order property is informational and nothing sorts by it). Here's a recommended production setup:","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Composing Middleware","lvl3":""}},
|
|
8035
8044
|
{"objectID":"293ec2d6d2933e2f370ee73b87ee9684f64143acd21d8bbb5e7e48640ec0d2bb","title":"Next Steps","url":"/docs/guides/server-adapters/middleware#next-steps","content":"Configuration Reference - Full server configuration options\nSecurity Best Practices - Authentication and authorization patterns\nDeployment Guide - Production deployment strategies\nExpress Adapter - Express-specific middleware integration\nFastify Adapter - Fastify-specific hooks and plugins","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Next Steps","lvl3":""}},
|
|
8036
8045
|
{"objectID":"3f8ed2c1cc0b9c59fe231fb08fe10302270284784b912664350299fe0a5de458","title":"Security Best Practices","url":"/docs/guides/server-adapters/security","content":"Security Best Practices\n\nProtect your AI APIs with comprehensive security measures\n\nThis guide covers authentication, authorization, rate limiting, and other security best practices for deploying NeuroLink server adapters in production.\n\nAuthentication\n\nNeuroLink server adapters support multiple authentication strategies out of the box.\n\nBearer Token Authentication\n\nBearer tokens (JWT, OAuth tokens) are the most common authentication method for APIs:\n\nAPI Key Authentication\n\nFor service-to-service communication or simple API access:\n\nBasic Authentication\n\nFor simple username/password authentication:\n\nCustom Authentication\n\nFor OAuth 2.0, OIDC, or custom schemes:\n\nCarrying middleware state to guards and handlers (carryMiddlewareState)\n\nAuthentication middleware sets ctx.user. On the built-in adapters, whether the\nmiddleware that runs after it, and the route handler, see it depends on the\nadapter and on carryMiddlewareState, which is off by default: each adapter\nthen propagates context as it always did. Express, Fastify and Koa build a fresh\ncontext for every middleware step and for the handler and carry only the\nresponse headers; Hono shares one context between the steps and the handler only\nwhen the client sent its own X-Request-ID.\n\nThe option does not apply to a context you build yourself: a custom adapter, or a\nroute handler you call directly, can supply a context that already has ctx.user\nset.\n\nSo by default a role guard (createRoleMiddleware) registered after\ncreateAuthMiddleware sees the user on one request shape only. Measured: it\nanswers 401 to every request on Express, Fastify and Koa, and on Hono without a\nclient X-Request-ID, even for a user holding the required role, and a\nrate-limit keyGenerator reads ctx.user as undefined there. Set the option on\nthe server to carry ctx.user, ctx.session, ctx.metadata and the abort\nsignal to later middleware and the handler on every built-in adapter:\n\nWith it on, the role guard admits a user holding the role (200) and refuses one\nwithout it (403), and a keyGenerator sees ctx.user, on every built-in adapter. A key\ngenerator that keys on the user id then does what it says, so make it ignore a\nshared identity (ctx.user.shared), or every holder of one API key falls into a\nsingle bucket; the rate-limit examples below do. Turning the option on does not\nchange whose identity the agent routes trust, and registerAllRoutes turns it\non by itself when given perUserAuth, as the next section says.\n\nWho the agent routes treat as the user (perUserAuth)\n\nWhether the agent routes (/agent/execute, /agent/stream, and the skill\nmutation routes' requestedBy) and the memory routes (/memory/*) trust\nctx.user as a person is a separate choice from whether the server carries it:\na single shared API key sets the same ctx.user for every caller, and taking it\nas the user would give every client one userId and no conversation memory\n(agent routes), or make every client a non-admin of its own deployment (memory\nroutes).\n\nSo without an opt-in the agent routes resolve identity as they always have:\nOn Express, Fastify and Koa, and on Hono when the client sent no\n X-Request-ID, userId and sessionId come from the request body.\n ctx.user and ctx.session are ignored (they are not in the handler's\n context at all unless the server carries middleware state), and the skill\n routes use the body's requestedBy.\nOn Hono, when the client sent its own X-Request-ID header, an authenticated\n ctx.user wins over the body (and ctx.session over the body's\n sessionId), as it did before. Hono kept the middleware's context under that\n header, so the handler found it. That is the only built-in combination where\n the default ever guarded userId.\nA context the built-in adapters did not hand the carry to keeps the same\n rule, an authenticated ctx.user wins: an adapter you wrote that sets\n ctx.user itself, or a route handler you call directly with a context you\n built (a test harness, for one).\n\nThe memory routes have none of these exceptions: without the opt-in they ignore\nctx.user on every adapter and for every request.\n\nSet perUserAuth: true when your middleware identifies individual people (one\ncredential per person). Only this option, with carryMiddlewareState on, makes the agent routes take\nthe user from ctx.user, and ignore the body's userId, on every built-in\nadapter and for every request:\n\nregisterAllRoutes also turns on carryMiddlewareState for the server, because\nthe routes can only take identity from ctx.user if the adapter hands it to the\nhandler. With carryMiddlewareState on, a perUserAuth request that your middleware\nauthenticated reaches the handler with that user on every built-in adapter. A\nrequest that no middleware authenticated (optional authentication) runs as\nanonymous, with no userId and no session.\n\nIf you register the agent routes yourself with\ncreateAgentRoutes(\"/api\", { perUserAuth: true }), create the server with\ncarryMiddlewareState: true. Without it, whether a perUserAuth request","hierarchy":{"lvl0":"Guides","lvl1":"Security Best Practices","lvl2":"","lvl3":""}},
|
|
8037
8046
|
{"objectID":"7cdb3cd74c088f4b197de4db297c2eb3b47c353b41ce1a84ed2e12548147b408","title":"Security Best Practices","url":"/docs/guides/server-adapters/security#security-best-practices","content":"Protect your AI APIs with comprehensive security measures\n\nThis guide covers authentication, authorization, rate limiting, and other security best practices for deploying NeuroLink server adapters in production.","hierarchy":{"lvl0":"Guides","lvl1":"Security Best Practices","lvl2":"Security Best Practices","lvl3":""}},
|
|
@@ -9905,7 +9914,7 @@
|
|
|
9905
9914
|
{"objectID":"677188568d1a1f62404df0b7a4c3655f9e19f645c9918030d046d433a6429339","title":"Core Options","url":"/docs/reference/server-configuration#core-options","content":"| Option | Type | Default | Description |\n| ---------------------- | --------- | ------------- | --------------------------------------------------------------------------------------------------------------- |\n| port | number | 3000 | Server port to listen on |\n| host | string | \"127.0.0.1\" | Interface to bind; loopback by default. \"0.0.0.0\" listens on every interface — register authentication first |\n| basePath | string | \"/api\" | Base path prefix for all routes |\n| timeout | number | 30000 | Per-request timeout, on every adapter: a request past it is answered 504 REQUEST_TIMEOUT and its work aborted |\n| enableMetrics | boolean | true | Enable metrics endpoint |\n| enableSwagger | boolean | false | Enable OpenAPI/Swagger documentation (see below) |\n| disableBuiltInHealth | boolean | false | Disable built-in health routes |","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Core Options","lvl3":""}},
|
|
9906
9915
|
{"objectID":"679f1af42104e68e108d5e6009e16718cab67c8d2f3712b45dc516ba333b9c27","title":"OpenAPI/Swagger Documentation (enableSwagger)","url":"/docs/reference/server-configuration#openapiswagger-documentation-enableswagger","content":"When enableSwagger is set to true, the server exposes interactive API documentation endpoints:\n\n| Endpoint | Description |\n| ----------------------------- | ---------------------------------------- |\n| GET {basePath}/openapi.json | OpenAPI 3.1 specification in JSON format |\n| GET {basePath}/openapi.yaml | OpenAPI 3.1 specification in YAML format |\n| GET {basePath}/docs | Interactive Swagger UI documentation |\n\nExample URLs (with default basePath /api):\nhttp://localhost:3000/api/openapi.json\nhttp://localhost:3000/api/openapi.yaml\nhttp://localhost:3000/api/docs\n\nThe Swagger UI provides an interactive interface where you can:\nBrowse all available API endpoints\nView request/response schemas\nTest API calls directly from the browser\nDownload the OpenAPI specification\n\nSecurity Consideration: In production environments, consider disabling enableSwagger to prevent exposing internal API structure. Alternatively, protect the documentation endpoints with authentication middleware.","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"OpenAPI/Swagger Documentation (enableSwagger)","lvl3":""}},
|
|
9907
9916
|
{"objectID":"4521fc87cb580735f24e75ac3b75c56ddf87507e23597fbd438cb953ec71544a","title":"Example: Basic Configuration","url":"/docs/reference/server-configuration#example-basic-configuration","content":"Example: Basic Configuration","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Example: Basic Configuration","lvl3":""}},
|
|
9908
|
-
{"objectID":"a70d025b0c2289499401bc2bc4e8071a199c148ac4483d5a3e646d713509c2ef","title":"CORS Configuration","url":"/docs/reference/server-configuration#cors-configuration","content":"| Option | Type | Default
|
|
9917
|
+
{"objectID":"a70d025b0c2289499401bc2bc4e8071a199c148ac4483d5a3e646d713509c2ef","title":"CORS Configuration","url":"/docs/reference/server-configuration#cors-configuration","content":"| Option | Type | Default | Description |\n| ------------- | ---------- | ------------------------------------------------------------------- | ------------------------------------------------------ |\n| enabled | boolean | true | Enable CORS support |\n| origins | string[] | [] | Allowed origins ([\"*\"] = any) |\n| methods | string[] | [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"] | Allowed HTTP methods |\n| headers | string[] | [\"Content-Type\", \"Authorization\", \"X-Request-ID\", \"X-Session-Id\"] | Allowed headers (a list you pass replaces the default) |\n| credentials | boolean | false | Allow credentials |\n| maxAge | number | 86400 | Preflight cache max age in seconds |\n\nX-Session-Id is the header createSessionMiddleware() reads. That middleware does nothing on a server that does not carry middleware state (carryMiddlewareState, off by default), except on Hono for a request whose client sent its own X-Request-ID, which shares one context with the handler either way; registerAllRoutes with perUserAuth turns the carry on, or set carryMiddlewareState: true on the server. See the middleware guide.\n\nSecurity note: With no origins listed, no web page can call the server cross-origin. List the origins you serve pages from, or set [\"*\"] explicitly to allow any domain (then also set an API key). neurolink serve --cors-origin https://myapp.com does the same from the command line.","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"CORS Configuration","lvl3":""}},
|
|
9909
9918
|
{"objectID":"708cea96fded6a3d6b4ae7e87e0edd070731d631cb4d87c2684792a82addbb0c","title":"Example: Restrictive CORS","url":"/docs/reference/server-configuration#example-restrictive-cors","content":"Example: Restrictive CORS","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Example: Restrictive CORS","lvl3":""}},
|
|
9910
9919
|
{"objectID":"3706f16eed022d7b144945eae7c4e22925c2d8aa62896bbc81097cab7b4875e2","title":"Rate Limit Configuration","url":"/docs/reference/server-configuration#rate-limit-configuration","content":"| Option | Type | Default | Description |\n| ---------------- | ---------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| enabled | boolean | true | Enable rate limiting |\n| windowMs | number | 900000 (15 min) | Time window in milliseconds |\n| maxRequests | number | 100 | Maximum requests per window |\n| message | string | \"Too many requests...\"","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Rate Limit Configuration","lvl3":""}},
|
|
9911
9920
|
{"objectID":"06f1efd322182e016ace893db5f7332ce70ca77362234b7d38a3fc3d924264b4","title":"Example: Custom Rate Limiting","url":"/docs/reference/server-configuration#example-custom-rate-limiting","content":"Example: Custom Rate Limiting","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Example: Custom Rate Limiting","lvl3":""}},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "13.
|
|
3
|
+
"version": "13.9.0",
|
|
4
4
|
"packageManager": "pnpm@10.34.9+sha512.f49b5a8ea0fdedb44bb3c0c1d6575092a53c2950d95b7ad15df11f17974877a2de3a01c07e934e9b28ce716e51c09a94962c7306d09be2e1e4b18a8c8762fd32",
|
|
5
5
|
"description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
|
|
6
6
|
"author": {
|
|
@@ -217,6 +217,7 @@
|
|
|
217
217
|
"test:body-limits": "pnpm exec tsx test/continuous-test-suite-body-limits.ts",
|
|
218
218
|
"test:adapter-request-context": "pnpm exec tsx test/continuous-test-suite-adapter-request-context.ts",
|
|
219
219
|
"test:memory-route-scope": "pnpm exec tsx test/continuous-test-suite-memory-route-scope.ts",
|
|
220
|
+
"test:session-middleware": "pnpm exec tsx test/continuous-test-suite-session-middleware.ts",
|
|
220
221
|
"test:websocket-agent-handler": "pnpm exec tsx test/continuous-test-suite-websocket-agent-handler.ts",
|
|
221
222
|
"test:tool-reliability": "pnpm exec tsx test/continuous-test-suite-tool-reliability.ts",
|
|
222
223
|
"test:video-abort": "pnpm exec tsx test/continuous-test-suite-video-abort.ts",
|